############################################################################################################################################
# The Cultural Origins of Populism ----------------------------
# Yotam Margalit, Shir Raviv and Omer Solodoch  ---------------------------
# This R file contains the code necessary to replicate the analysis in the supplementary appendix. ----------------------------
# R version 4.1.2 (2021-11-01) 
# Running under: macOS 14.1.2
############################################################################################################################################
# Clear environment and return memory to the operating system ---------
rm(list = ls())
gc()

# Installing and loading needed packages -----------
#Load required R packages (download first if necessary)
packages_required <- c('kableExtra','forcats','survey','jtools','tibble',
                       'knitr','scales','purrr','base','generics','broom',
                       'srvyr', 'stargazer', 'lmtest', 'haven', 'expss', 'dplyr', 'rmarkdown', 'psych', 'gt','readxl','broom','ggplot2',
                       'ivmte', 'ggpubr', 'writexl', 'rio', 'patchwork', 'Lahman', 'cregg', 'xtable', 'ggmosaic'
)

# Function to check and install any missing packages
install_and_load_packages <- function(packages) {
  for (package in packages) {
    if (!require(package, character.only = TRUE)) {
      install.packages(package)
      library(package, character.only = TRUE)
    }
  }
}
# Apply the function to the list of required packages
install_and_load_packages(packages_required)


# Set Working Directory  ############
# Set the working directory where the data is stored and where to save outputs
setwd("insert here.. /JOP Replication")
plotpath<-"figures/"

# Loud the clean data ---------
ess_data <- readRDS("data/ESS_69_newvars.rds")

## ---------------------- Table  SI-1 Number of observations by EU Country ----------------------
# Calculate the weighted and unweighted number of observations per country
observations_table <- ess_data %>%
  group_by(cntry) %>%
  summarise(
    weighted_n = sum(fullweight, na.rm = TRUE),
    unweighted_n = n()
  )
observations_table
# Calculate the total weighted and unweighted observations
total_observations <- observations_table %>%
  summarise(
    total_weighted = sum(weighted_n),
    total_unweighted = sum(unweighted_n)
  )
total_observations
## ---------------------- Table  SI-2 Summary Statistics - ESS Data ----------------------
subset_ess_data <- ess_data %>%
  dplyr::select(ethnic_minority, born_incountry, older55, Rural_area,Male,
                below_2median_income, difficult_subj, production_worker,unemployed_lookingforjob,
                low_education, White_Native_img_undermined_cult, 
                older55_authoritarian, rural_have_no_voice2,
                social_status25_respect2, distant_people_local_noturban)
# Function to calculate descriptive statistics
calculate_stats <- function(x) {
  c(mean = round(mean(x, na.rm = TRUE), 3), 
    sd = round(sd(x, na.rm = TRUE), 3), 
    N = sum(!is.na(x)))
}
descriptive_stats_table <- as.data.frame(lapply(subset_ess_data, calculate_stats))
descriptive_stats_table <- t(descriptive_stats_table)
colnames(descriptive_stats_table) <- c("Mean", "SD", "N")
print(descriptive_stats_table)

## ---------------------- Figure SI-1 Vote Share for Right-Wing Populist Parties Across European Countries, 1960–2020 -------------
electionpop <- read_excel("data/elections_10countries_PopuList.xlsx")


electionpop$country2<-factor(electionpop$country, levels = c("Switzerland","Germany","Denmark",
                                                             "France","United Kingdom",
                                                             "Hungary","Italy","Netherlands","Poland","Sweden" ))
Fig_SI1_B<-electionpop %>%
  filter(country %in% c("Germany", "Denmark", "France", "United Kingdom", "Sweden")) %>%
  ggplot() +
  aes(x = year, y = populist, colour = country2) +
  geom_line(size = 0.7) +
  geom_point(size = 0.7) +
  scale_colour_manual(values = c("#83a9b9","#5b808f","#264653","#2a9d8f","#469572" ))+
  scale_x_continuous(limit=c(1960, 2020), breaks=c(1960, 1980, 2000, 2020))+
  scale_y_continuous(limit=c(0, 40), labels = function(x) paste0(x, "%"))+
  labs(x = " ", y = " ") + 
  theme_minimal() +  theme(legend.position = "none",
                           panel.spacing = unit(1.7, "lines"),
                           strip.text.x = element_text(size = 14),
                           axis.text = element_text(size = 14))+
  facet_wrap(vars(country2), nrow=1)

Fig_SI1_A<-electionpop %>%
  filter(!(country %in% c("Germany", "Denmark", "France", "United Kingdom", "Sweden"))) %>%
  ggplot() +
  aes(x = year, y = populist, colour = country2) +
  geom_line(size = 0.7) +
  geom_point(size = 0.7) +
  scale_colour_manual(values = c("#8cb380","#e9c46a","#f4a261","#e76f51","#c53d1b"))+
  scale_x_continuous(limit=c(1960, 2020), breaks=c(1960, 1980, 2000, 2020))+
  scale_y_continuous(labels = function(x) paste0(x, "%"))+
  labs(x = " ", y = " ") +   
  theme_minimal() + theme(legend.position = "none",
                          panel.spacing = unit(1.7, "lines"),
                                strip.text.x = element_text(size = 14),
                                axis.text = element_text(size = 14))+
  facet_wrap(vars(country2), nrow=1)

Fig_SI1<- ggarrange( Fig_SI1_B, Fig_SI1_A,
                              ncol = 1, nrow = 2)

ggsave(Fig_SI1, dpi = 600,
       filename = paste0(plotpath, "Fig_SI1.tif"),        
       device = "tiff",
       height = 6, width = 12)

## ---------------------- Figure SI-2 Including Radical Right Non-Populist Parties -------------

# Regression analyses
fit_RWPP <- lm(vote_choice_PopList_RightPop ~ social_status25_respect2 + rural_resentment_trust + older55_authoritarian + White_Native_img_undermined_cult + distant_people_local_noturban+cntry+essround,
               data = ess_data, weights = fullweight)

fit_RRP <- lm(vote_Rad_RightPop ~ social_status25_respect2 + rural_resentment_trust + older55_authoritarian + White_Native_img_undermined_cult + distant_people_local_noturban+cntry+essround,
               data = ess_data, weights = fullweight)


# Tidy the results of regression models
tidy_RWPP <- tidy(fit_RWPP)
tidy_RRP <- tidy(fit_RRP)

# Filter results to include only coefficients of interest
coefficients_of_interest <- c("social_status25_respect2", "rural_resentment_trust", "older55_authoritarian", "White_Native_img_undermined_cult", "distant_people_local_noturban")

tidy_RWPP <- tidy_RWPP %>% filter(term %in% coefficients_of_interest)
tidy_RRP <- tidy_RRP %>% filter(term %in% coefficients_of_interest)

# Create a data frame combining all results
data_Fig_SI2 <- bind_rows(
  mutate(tidy_RWPP, Model = "Right-Wing Populist"),
  mutate(tidy_RRP, Model = "Right-Wing Populist and Radical Right")
  )

data_Fig_SI2<-data_Fig_SI2%>% 
  filter(term %in% c("White_Native_img_undermined_cult", 
                     "older55_authoritarian", "rural_have_no_voice2",
                     "distant_people_local_noturban", "social_status25_respect2")) %>%
  mutate(term=case_when(
    term=="White_Native_img_undermined_cult"~"Ethno-Cultural Estrangement",
    term=="older55_authoritarian"~"Intergenerational Backlash",
    term=="rural_have_no_voice2"~"Rural Resentment",
    term=="social_status25_respect2"~"Social Status Anxiety",
    term=="distant_people_local_noturban"~"Community Disintegration"
  )) 

Fig_SI2<-
  data_Fig_SI2 %>%  
  ggplot()+aes(term, estimate, fill=Model, color=Model, shape=Model)+ 
  geom_hline(yintercept=0, linetype=2, lwd=0.9, size=1.3, colour = "#ACBBBF", alpha=0.9) +
  geom_errorbar(stat = "identity", alpha = 0.5, 
                position = position_dodge(width = 0.2),
                aes(ymin=estimate - 1.96*std.error, ymax=estimate + 1.96*std.error),
                lwd=1.2, width = 0)+
  geom_errorbar(stat = "identity", alpha = 0.8, 
                position = position_dodge(width = 0.2),
                aes(ymin=estimate - 1.64*std.error, ymax=estimate + 1.64*std.error), 
                lwd=1, width=0) +
  scale_colour_manual(values = c("#E84F5C","#96051A"))+
  scale_fill_manual(values = c("#E84F5C","#96051A"))+
  geom_point(stat = "identity", alpha = 0.7,  
             size = 1.8, position = position_dodge(width = 0.2)) + 
  guides(shape = FALSE)+
  coord_flip() + 
  labs(x = "", y = " ", subtitle = "", shape="") +
  theme_minimal() + theme(legend.position = "bottom",    
                          text= element_text(size = 13.5),
                          plot.background = element_rect(fill = "white", colour = "white"),
                          plot.margin = unit(c(0, 0, 0.5, 0), "cm"),
                          panel.spacing = unit(1, "lines"))

Fig_SI2

ggsave(Fig_SI2, dpi = 600,
       filename = paste0(plotpath, "Fig_SI2.tif"), device = "tiff",
       height = 5, width = 8)

## ---------------------- Table  SI-5 Demographic Predictors of Voting for Populist Parties, by Country ----------
# A function to fit the linear model for a country
fit_country_model <- function(data, country) {
  lm(vote_choice_PopList_RightPop ~                
       older55 + Rural_area + low_education +
       below_2median_income + very_relig + factor(Wave),
     weights = fullweight,    
     data = subset(data, cntry == country))
}

# List of countries
countries <- c("Switzerland", "Denmark", "France", "Hungary", "Italy",
               "Poland", "Netherlands", "Sweden", "United Kingdom", "Germany")

# Fit the model for each country
models <- lapply(countries, function(country) fit_country_model(ess_data, country))
names(models) <- countries

# Use stargazer with the list of models
stargazer(models,
          column.labels = countries,
          omit = "Wave",
          covariate.labels = c("Older (55+)",
                               "Rural residents",
                               "Low education",
                               "Low income",
                               "Religious",
                               "Constant"),
          type = "latex",
          dep.var.labels = c("Voting for Populist Parties"),
          title = "Interaction between cultural and economic concerns, by country - 2012",
          omit.stat = c('adj.rsq', 'ser', 'f'),
          star.cutoffs = c(0.05, 0.01, 0.001), star.char = c('*','**','***'),
          notes = '*p<0.05; **p<0.01; ***p<0.001', notes.append = FALSE, no.space = TRUE,  align = TRUE)

## ---------------------- Figure SI-3 Share of working-class white males, by support for right-wing populist parties -------
# Create new variables for "White male & low edu"
ess_data$white_lowedu<- as.numeric (with(ess_data, ifelse ((low_education==1 &
                                                              Male==1 &
                                                              ethnic_minority==0),1,0)))

ess_data$white_lowedu[is.na(ess_data$low_education) |
                        is.na(ess_data$Male) |
                        is.na(ess_data$ethnic_minority)] <- NA

# Create new variables for "White male & low edu & low inc"
ess_data$white_lowedu_lowincome<- as.numeric (with(ess_data, ifelse ((low_education==1 &
                                                                        Male==1 & 
                                                                        ethnic_minority==0 &
                                                                        below_2median_income==1),1,0)))

ess_data$white_lowedu_lowincome[is.na(ess_data$low_education) |
                                  is.na(ess_data$Male) |
                                  is.na(ess_data$ethnic_minority) |
                                  is.na(ess_data$below_2median_income)   ] <- NA


# Create new variables for "White male & low edu & production"
ess_data$white_lowedu_lowedu_production<- as.numeric (with(ess_data, ifelse ((low_education==1 &
                                                                                Male==1 & ethnic_minority==0&
                                                                                production_worker==1),1,0)))

ess_data$white_lowedu_lowedu_production[is.na(ess_data$low_education) |
                                          is.na(ess_data$Male) |
                                          is.na(ess_data$ethnic_minority) |
                                          is.na(ess_data$production_worker)   ] <- NA


#  Calculate mean 
calculate_mean <- function(var, data) {
  var_name <- as.name(var)
  data %>%
    dplyr::filter(!is.na(!!var_name)) %>%
    as_survey_design(weights = c(fullweight)) %>%
    dplyr::group_by(cntry,vote_RightPop_factor) %>%
    dplyr::summarize(n = survey_mean(!!var_name, na.rm = FALSE, vartype = "ci"))
}

white_lowedu_data <- calculate_mean("white_lowedu", ess_data)
white_lowedu_lowincome_data <- calculate_mean("white_lowedu_lowincome", ess_data)
white_lowedu_lowedu_production_data <- calculate_mean("white_lowedu_lowedu_production", ess_data)

fig_econ_maleworkingclass <- bind_rows(
  white_lowedu_data,
  white_lowedu_lowincome_data,
  white_lowedu_lowedu_production_data,
  .id="Characteristic")

fig_econ_maleworkingclass$Characteristic<-factor(fig_econ_maleworkingclass$Characteristic, levels=c(1,2,3),
                                                 labels=c(
                                                   "White male & low edu",
                                                   "White male & low edu & low inc",
                                                   "White male & low edu & production"
                                                 ))
fig_econ_maleworkingclass$vote_RightPop_factor<-factor(fig_econ_maleworkingclass$vote_RightPop_factor)
fig_econ_maleworkingclass$vote_RightPop_factor <- relevel(fig_econ_maleworkingclass$vote_RightPop_factor, ref = "Right Wing Populist Parties")

Fig_SI3<-fig_econ_maleworkingclass %>%
  mutate(Characteristic = fct_reorder(Characteristic, desc(n))) %>%
  ggplot()+aes(x=Characteristic,y=n,fill=vote_RightPop_factor,colour=vote_RightPop_factor)+
  geom_col(alpha=0.9,width=0.5, position = position_dodge(width=0.7))+
  geom_errorbar(aes(ymin = n, ymax = n_upp), position = position_dodge(width=0.7),
                width = 0.5, lwd=0.4, color="gray40") +
  scale_fill_manual(values = c("#A20021", "#97C1D1"))+
  scale_colour_manual(values = c("#A20021", "#97C1D1"))+
  scale_y_continuous(labels=scales::percent, limits = c(0, 0.75)) +
  labs(x = " ", y = "", fill = "", color = "") +  coord_flip()+
  theme_minimal() +facet_wrap(facets=~cntry,nrow=2)+
  theme(legend.position = "bottom", legend.text = element_text(size=11),
        legend.margin = margin(t = -10, unit = "pt"), 
        strip.text.x = element_text(size = 13),
        axis.text = element_text(size = 13),
        axis.text.x = element_text(size = 10),
        plot.background = element_rect(fill = "white", colour = "white"),
        plot.margin = unit(c(0, 1, 0.5, 0), "cm"),
        panel.spacing = unit(0.5, "lines"))
ggsave(Fig_SI3, dpi = 600,
       filename = paste0(plotpath, "Fig_SI3.tif"), device = "tiff",
       height = 6, width = 11)

## ---------------------- Figure SI-4 Economic insecurity, by support for right-wing populist parties --------
ess_data$low_econ_edu<- as.numeric (with(ess_data, ifelse ((low_education==1 &
                                                              below_2median_income==1),1,0)))
ess_data$low_econ_edu[is.na(ess_data$low_education) |
                        is.na(ess_data$below_2median_income)  ] <- NA

calculate_mean <- function(var, data) {
  var_name <- as.name(var)
  data %>%
    dplyr::filter(!is.na(!!var_name)) %>%
    as_survey_design(weights = c(fullweight)) %>%
    dplyr::group_by(cntry,vote_RightPop_factor) %>%
    dplyr::summarize(n = survey_mean(!!var_name, na.rm = FALSE, vartype = "ci"))
}

econ_inse_subj_data<- calculate_mean("difficult_subj", ess_data)
low_econ_edu_data <- calculate_mean("low_econ_edu", ess_data)
econ_inse_obj_data <- calculate_mean("econ_inse_obj", ess_data)
low_income_data <- calculate_mean("below_2median_income", ess_data)

data_Fig_SI4 <- bind_rows(
  econ_inse_subj_data,
  low_econ_edu_data,
  econ_inse_obj_data,
  low_income_data,
  .id="Characteristic")

data_Fig_SI4$Characteristic<-factor(data_Fig_SI4$Characteristic, levels=c(1,2,3,4),
                                   labels=c("Economically insecure (subj.)",
                                            "Low income with Low education",
                                            "Unemployed / occupation threatened",
                                            "Low income"))
data_Fig_SI4$vote_RightPop_factor<-factor(data_Fig_SI4$vote_RightPop_factor)
data_Fig_SI4$vote_RightPop_factor <- relevel(data_Fig_SI4$vote_RightPop_factor, ref = "Right Wing Populist Parties")

Fig_SI4<-data_Fig_SI4 %>%
  mutate(Characteristic = fct_reorder(Characteristic, desc(n))) %>%
  ggplot()+aes(x=Characteristic,y=n,fill=vote_RightPop_factor,colour=vote_RightPop_factor)+
  geom_col(alpha=0.9,width=0.5, position = position_dodge(width=0.7))+
  geom_errorbar(aes(ymin = n, 
                    ymax = n_upp), position = position_dodge(width=0.7),
                width = 0.5, lwd=0.4, color="gray40") +
  scale_fill_manual(values = c("#A20021", "#97C1D1"))+
  scale_colour_manual(values = c("#A20021", "#97C1D1"))+
  scale_y_continuous(labels=scales::percent, limits = c(0, 0.75)) +
  labs(x = " ", y = "", 
       fill = "", color = "") +  coord_flip()+
  theme_minimal() +facet_wrap(facets=~cntry,nrow=2)+
  theme(legend.position = "bottom", legend.text = element_text(size=11),
        legend.margin = margin(t = -10, unit = "pt"), 
        strip.text.x = element_text(size = 13),
        axis.text = element_text(size = 13),
        axis.text.x = element_text(size = 10),
        plot.background = element_rect(fill = "white", colour = "white"),
        plot.margin = unit(c(0, 1, 0.5, 0), "cm"),
        panel.spacing = unit(0.5, "lines"))
Fig_SI4


ggsave(Fig_SI4, dpi = 600,
       filename = paste0(plotpath, "Fig_SI4.tif"), device = "tiff",
       height = 6, width = 11)


## ---------------------- Figure SI-5 Share of populist voters by number of cultural storylines their characteristics match --------
# Select relevant variables
data_SI5<-ess_data %>%
  dplyr::select(idno, Wave, cntry, fullweight, vote_choice_PopList_RightPop, vote_RightPop_factor, 
                White_Native_img_undermined_cult, 
                older55_authoritarian, rural_have_no_voice2, social_status25_respect2, distant_people_local_noturban,
                unemployed_lookingforjob, production_worker, below_2median_income, difficult_subj )

# Filter the data for the 2012 wave and calculate a summary score of cultural concerns.
data_SI5_sumcult<-data_SI5 %>%
  filter(Wave %in% c("2012")) %>%
  rowwise() %>%
  mutate(sum_stories_cult = sum(White_Native_img_undermined_cult, 
                                older55_authoritarian, 
                                social_status25_respect2, 
                                distant_people_local_noturban, na.rm = TRUE))

# Assign a binary indicator for the presence of cultural concerns.
data_SI5_sumcult$culturalconcern<- as.numeric (with(data_SI5_sumcult, ifelse ((sum_stories_cult!=0),1,0)))
# Assign NA where the summary score is missing.
data_SI5_sumcult$culturalconcern[is.na(data_SI5_sumcult$sum_stories_cult) ] <- NA

# Filter out respondents with no cultural concerns.
data_SI5_sumcult<-subset(data_SI5_sumcult, culturalconcern==1)

# Create binary indicators for the number of cultural concerns (1 concern)
data_SI5_sumcult$culturalconcern1<- as.numeric (with(data_SI5_sumcult, ifelse ((sum_stories_cult==1 ),1,0)))
pop_culturalconcern1 <- data_SI5_sumcult %>%
  filter(!is.na(vote_choice_PopList_RightPop)) %>%
  as_survey_design(weights = c(fullweight)) %>%
  dplyr::group_by(cntry,vote_choice_PopList_RightPop) %>%
  dplyr::summarize(n = survey_mean(culturalconcern1, na.rm = FALSE, vartype = "ci")) %>%
  filter(vote_choice_PopList_RightPop==1)

# Create binary indicators for the number of cultural concerns (2 concerns)
data_SI5_sumcult$culturalconcern2<- as.numeric (with(data_SI5_sumcult, ifelse ((sum_stories_cult==2 ),1,0)))
data_SI5_sumcult$culturalconcern2[is.na(data_SI5_sumcult$sum_stories_cult) ] <- NA
pop_culturalconcern2 <- data_SI5_sumcult %>%
  filter(!is.na(vote_choice_PopList_RightPop)) %>%
  as_survey_design(weights = c(fullweight)) %>%
  dplyr::group_by(cntry,vote_choice_PopList_RightPop) %>%
  dplyr::summarize(n = survey_mean(culturalconcern2, na.rm = FALSE, vartype = "ci")) %>%
  filter(vote_choice_PopList_RightPop==1)

# Create binary indicators for the number of cultural concerns (3 concerns)
data_SI5_sumcult$culturalconcern3<- as.numeric (with(data_SI5_sumcult, ifelse ((sum_stories_cult==3 ),1,0)))
pop_culturalconcern3 <- data_SI5_sumcult %>%
  filter(!is.na(vote_choice_PopList_RightPop)) %>%
  as_survey_design(weights = c(fullweight)) %>%
  dplyr::group_by(cntry,vote_choice_PopList_RightPop) %>%
  dplyr::summarize(n = survey_mean(culturalconcern3, na.rm = FALSE, vartype = "ci")) %>%
  filter(vote_choice_PopList_RightPop==1)

# Create binary indicators for the number of cultural concerns (4 concerns)
data_SI5_sumcult$culturalconcern4<- as.numeric (with(data_SI5_sumcult, ifelse ((sum_stories_cult==4 ),1,0)))
pop_culturalconcern4 <- data_SI5_sumcult %>%
  filter(!is.na(vote_choice_PopList_RightPop)) %>%
  as_survey_design(weights = c(fullweight)) %>%
  dplyr::group_by(cntry,vote_choice_PopList_RightPop) %>%
  dplyr::summarize(n = survey_mean(culturalconcern4, na.rm = FALSE, vartype = "ci")) %>%
  filter(vote_choice_PopList_RightPop==1)


Fig_SI5_data <- bind_rows( pop_culturalconcern4,
                                                     pop_culturalconcern3,
                                                     pop_culturalconcern2,
                                                     pop_culturalconcern1,
                                                     .id="no.concerns")
Fig_SI5_data$no.concerns<-factor(Fig_SI5_data$no.concerns,
                                                           levels=c(1,2,3,4), labels=c( "4 Matches", 
                                                                                        "3", 
                                                                                        "2", 
                                                                                        "1 Match" ))
Fig_SI5_data<-Fig_SI5_data%>%
  mutate(prop=n*100)%>%
  mutate(propn_upp=n_upp*100)


Fig_SI5<-Fig_SI5_data %>%
  ggplot()+  aes(x = no.concerns, y = prop) +
  geom_col(alpha=0.8,width=0.5, position = position_dodge(width=0.7), fill="#990B25")+
  geom_errorbar(aes(ymin = prop, 
                    ymax = propn_upp), position = position_dodge(width=0.7),
                width = 0.5, lwd=0.4, color="gray40") +
  labs(x = " ", y = "", 
       fill = "", color = "") +  coord_flip()+
  theme_minimal() +facet_wrap(facets=~cntry,nrow=2)+
  theme(legend.position = "bottom", legend.text = element_text(size=11),
        legend.margin = margin(t = -10, unit = "pt"), 
        strip.text.x = element_text(size = 13),
        axis.text = element_text(size = 13),
        axis.text.x = element_text(size = 10),
        plot.background = element_rect(fill = "white", colour = "white"),
        plot.margin = unit(c(0, 1, 0.5, 0), "cm"),
        panel.spacing = unit(0.5, "lines"))
Fig_SI5
ggsave(Fig_SI5, dpi = 600,
       filename = paste0(plotpath, "Fig_SI5.tif"), device = "tiff",
       height = 6, width = 11)




## ---------------------- Table  SI-6 Correlation Matrix, ESS Round 6 -------

# Generating an alternative measure of rural resentment using items from round 6 to account for all ﬁve storylines in a single analysis. 
ess_data$less_turst<- as.numeric (with(ess_data, ifelse ((ess_data$trstprl<5),1,0))) 
ess_data$rural_resentment_trust<- as.numeric (with(ess_data, ifelse ((ess_data$Rural_area==1 & 
                                                                        ess_data$less_turst==1),1,0)))
ess_data$rural_resentment_trust[is.na(ess_data$less_turst) |  is.na(ess_data$Rural_area) ] <- NA

# Subst the sample to round 6 only
data_SI6<-ess_data %>%
  filter(Wave %in% c("2012")) %>%
  dplyr::select(idno, Wave, cntry, fullweight, 
                vote_choice_PopList_RightPop, vote_RightPop_factor, 
                White_Native_img_undermined_cult, 
                older55_authoritarian, rural_resentment_trust, social_status25_respect2, distant_people_local_noturban )

sapply(data_SI6[, c("social_status25_respect2", "White_Native_img_undermined_cult", 
              "older55_authoritarian", "rural_resentment_trust", 
              "distant_people_local_noturban")], function(x) {
                c(Summary = summary(x), Variance = var(x, na.rm = TRUE))
              })

# a. All voters
filtered_data <- data_SI6 %>% 
  dplyr::select(fullweight, social_status25_respect2, White_Native_img_undermined_cult, 
         older55_authoritarian, rural_resentment_trust, 
         distant_people_local_noturban) %>%
  na.omit()  # Remove rows with NA

# Now check variance again
sapply(filtered_data, var)

# Define the survey design object with weights, make sure to handle NA values
design <- svydesign(ids = ~1, data = filtered_data, weights = ~fullweight)

# Compute the correlation matrix for the selected variables, handling NA values
cor_matrix <- svycor(~ social_status25_respect2 + 
                       White_Native_img_undermined_cult + 
                       older55_authoritarian + 
                       rural_resentment_trust + 
                       distant_people_local_noturban,
                     digits = getOption("jtools-digits", default = 3),
                     design = design, na.rm = TRUE)
cor_matrix


# b. Populist-Right voters only

# Filter the data where vote_choice_PopList is 1 
filtered_data <- data_SI6 %>% 
  filter(vote_choice_PopList_RightPop == 1) %>%
  dplyr::select(fullweight, social_status25_respect2, White_Native_img_undermined_cult, 
         older55_authoritarian, rural_resentment_trust, 
         distant_people_local_noturban) %>%
  na.omit()  # Remove rows with NA

# Now check variance again
sapply(filtered_data, var)

# Define the survey design object with weights, make sure to handle NA values
design <- svydesign(ids = ~1, data = filtered_data, weights = ~fullweight)

# Compute the correlation matrix for the selected variables, handling NA values
cor_matrix <- svycor(~ social_status25_respect2 + 
                       White_Native_img_undermined_cult + 
                       older55_authoritarian + 
                       rural_resentment_trust + 
                       distant_people_local_noturban,
                       digits = getOption("jtools-digits", default = 3),
                       design = design, na.rm = TRUE)
cor_matrix

## ---------------------- Table  SI-7 Cultural Predictors of Voting for Populist Parties, by Country - 2018 --------
# Define variables
countries <- c("Switzerland", "Germany", "Denmark", "France", "United Kingdom", 
               "Hungary", "Italy", "Netherlands", "Poland", "Sweden")
models <- list()

# Process for each country
for (country in countries) {
  data_filtered <- ess_data %>%
    filter(Wave == "2018", cntry == country)
  
  models[[country]] <- lm(vote_choice_PopList_RightPop ~    
                            White_Native_img_undermined_cult +
                            older55_authoritarian +
                            rural_have_no_voice2,
                          weights = fullweight, 
                          data = data_filtered)
}

# Use stargazer for table creation
stargazer(models[[1]], models[[2]], models[[3]], models[[4]], models[[5]], 
          models[[6]], models[[7]], models[[8]], models[[9]], models[[10]],
          column.labels = countries,
          covariate.labels = c("Ethno-Cult Estrangement", "Intergen Backlash", "Rural Resentment"),
          type = "text",
          dep.var.labels = c("Voting for Populist Parties"),
          title = "Cultural Predictors of Voting for Populist Parties, by Country - 2018",
          omit.stat = c('adj.rsq', 'ser', 'f'),
          star.cutoffs = c(0.05, 0.01, 0.001), star.char = c('*', '**', '**'),
          notes = '*p<0.05; **p<0.01', notes.append = FALSE, no.space = TRUE, align = TRUE)


## ---------------------- Table  SI-8 Cultural Predictors of Voting for Populist Parties, by Country - 2016   --------
# Define variables
countries <- c("Switzerland", "Germany", "France", "United Kingdom", 
               "Hungary", "Italy", "Netherlands", "Poland", "Sweden")
models <- list()

# Process for each country
for (country in countries) {
  data_filtered <- ess_data %>%
    filter(Wave == "2016", cntry == country)
  
  models[[country]] <- lm(vote_choice_PopList_RightPop ~    
                            White_Native_img_undermined_cult+
                            older55_authoritarian+
                            rural_have_no_voice2,
                          weights = fullweight, 
                          data = data_filtered)
}

# Use stargazer for table creation
stargazer(models[[1]], models[[2]], models[[3]], models[[4]], models[[5]], 
          models[[6]], models[[7]], models[[8]], models[[9]], 
          column.labels = countries,
          covariate.labels = c("Ethno-Cult Estrangement", "Intergen Backlash", "Rural Resentment"),
          type = "text",
          dep.var.labels = c("Voting for Populist Parties"),
          title = "Cultural Predictors of Voting for Populist Parties, by Country - 2016",
          omit.stat = c('adj.rsq', 'ser', 'f'),
          star.cutoffs = c(0.05, 0.01, 0.001), star.char = c('*', '**', '**'),
          notes = '*p<0.05; **p<0.01', notes.append = FALSE, no.space = TRUE, align = TRUE)


## ---------------------- Table  SI-9 Cultural Predictors of Voting for Populist Parties, by Country - 2014  -------------
countries <- c("Switzerland", "Germany", "Denmark", "France", "United Kingdom", 
               "Hungary", "Netherlands", "Poland", "Sweden")
models <- list()

# Process for each country
for (country in countries) {
  data_filtered <- ess_data %>%
    filter(Wave == "2014", cntry == country)
  
  models[[country]] <- lm(vote_choice_PopList_RightPop ~    
                            White_Native_img_undermined_cult+
                            older55_authoritarian+
                            rural_have_no_voice2,
                          weights = fullweight, 
                          data = data_filtered)
}

# Use stargazer for table creation
stargazer(models[[1]], models[[2]], models[[3]], models[[4]], models[[5]], 
          models[[6]], models[[7]], models[[8]], models[[9]], 
          column.labels = countries,
          covariate.labels = c("Ethno-Cult Estrangement", "Intergen Backlash", "Rural Resentment"),
          type = "text",
          dep.var.labels = c("Voting for Populist Parties"),
          title = "Cultural Predictors of Voting for Populist Parties, by Country - 2014",
          omit.stat = c('adj.rsq', 'ser', 'f'),
          star.cutoffs = c(0.05, 0.01, 0.001), star.char = c('*', '**', '**'),
          notes = '*p<0.05; **p<0.01', notes.append = FALSE, no.space = TRUE, align = TRUE)






## ---------------------- Table  SI-10 Cultural Predictors of Voting for Populist Parties, by Country - 2012   --------
# Define variables
countries <- c("Switzerland", "Denmark", "France", 
               "Hungary", "Italy", "Netherlands", "Poland", "Sweden")
models <- list()

# Process for each country
for (country in countries) {
  data_filtered <- ess_data %>%
    filter(Wave == "2012", cntry == country)
  
  models[[country]] <- lm(vote_choice_PopList_RightPop ~    
                            White_Native_img_undermined_cult+
                            older55_authoritarian+
                            distant_people_local_noturban+
                            social_status25_respect2,
                          weights = fullweight, 
                          data = data_filtered)
}

# Use stargazer for table creation
stargazer(models[[1]], models[[2]], models[[3]], models[[4]], models[[5]], 
          models[[6]], models[[7]], models[[8]], 
          column.labels = countries,
          covariate.labels = c("Ethno-Cult Estrangement", "Intergen Backlash", "Rural Resentment"),
          type = "text",
          dep.var.labels = c("Voting for Populist Parties"),
          title = "Cultural Predictors of Voting for Populist Parties, by Country - 2012",
          omit.stat = c('adj.rsq', 'ser', 'f'),
          star.cutoffs = c(0.05, 0.01, 0.001), star.char = c('*', '**', '**'),
          notes = '*p<0.05; **p<0.01', notes.append = FALSE, no.space = TRUE, align = TRUE)

## ---------------------- Figure SI-7 Share of respondents who match the cultural accounts among right-wing populist versus center-right voters-------

calculate_mean <- function(var, data) {
  var_name <- as.name(var)
  data %>%
    dplyr::filter(!is.na(!!var_name)) %>%
    as_survey_design(weights = c(fullweight)) %>%
    dplyr::group_by(cntry,vote_choice_CentralRight) %>%
    dplyr::summarize(n = survey_mean(!!var_name, na.rm = FALSE, vartype = "ci"))
}

White_Native_img_undermined_cult_pop <- calculate_mean("White_Native_img_undermined_cult", ess_data)
older55_authoritarian_pop <- calculate_mean("older55_authoritarian", ess_data)
rural_have_no_voice2_pop <- calculate_mean("rural_have_no_voice2", ess_data)
social_status25_respect2_pop <- calculate_mean("social_status25_respect2", ess_data)
distant_people_local__noturban_pop <- calculate_mean("distant_people_local_noturban", ess_data)

figSI7_culturalstories <- bind_rows( White_Native_img_undermined_cult_pop,
                                   older55_authoritarian_pop,
                                   rural_have_no_voice2_pop,
                                   distant_people_local__noturban_pop,
                                   social_status25_respect2_pop,
                                   .id="Characteristic")


figSI7_culturalstories$Characteristic<-factor(figSI7_culturalstories$Characteristic, 
                                            levels=c(1,2,3,4,5),
                                            labels=c("Ethno-Cultural Estrangement",
                                                     "Intergenerational Backlash",
                                                     "Rural Resentment",
                                                     "Community Disintegration",
                                                     "Social Status Anxiety"))

figSI7<-figSI7_culturalstories %>%
    mutate(Characteristic = fct_reorder(Characteristic, desc(n))) %>%
  ggplot()+aes(x=Characteristic,y=n,label=n,fill=vote_choice_CentralRight,colour=vote_choice_CentralRight)+
  geom_col(alpha=0.9,width=0.5, position = position_dodge(width=0.7))+
  geom_errorbar(aes(ymin = n, 
                    ymax = n_upp), position = position_dodge(width=0.7),
                width = 0.5, lwd=0.4, color="gray40") +
  scale_fill_manual(values = c("#A3B8CC", "#A20021", "#B5888E"))+
  scale_colour_manual(values = c("#A3B8CC", "#A20021", "#B5888E"))+
  scale_y_continuous(labels=scales::percent) +
  labs(x = " ", y = "", subtitle = "", title="", 
       fill = "", color = "") +  coord_flip()+
  theme_minimal() +facet_wrap(facets=~cntry,nrow=2)+
  theme(legend.position = "bottom", legend.text = element_text(size=11),
        legend.margin = margin(t = -10, unit = "pt"), 
        strip.text.x = element_text(size = 13),
        axis.text = element_text(size = 13),
        axis.text.x = element_text(size = 10),
        plot.background = element_rect(fill = "white", colour = "white"),
        plot.margin = unit(c(0, 1, 0.5, 0), "cm"),
        panel.spacing = unit(0.5, "lines"))
figSI7
ggsave(figSI7, dpi = 600,
       filename = paste0(plotpath, "Fig_SI7.tif"), device = "tiff",
       height = 6, width = 11)


## ---------------------- Figure SI-8 Share of Voters by Proﬁle and Populist Support -----
ess_data$no_pop_party<- as.numeric (with(ess_data, ifelse (((cntry=="Germany" & Wave=="2012") | 
                                                              (cntry=="United Kingdom" & Wave=="2012") | 
                                                              (cntry=="Italy" & Wave=="2014")| 
                                                              (cntry=="Denmark"  &  Wave=="2016")),1,0)))
ess_data$no_pop_party[is.na(ess_data$cntry) | 
                        is.na(ess_data$cntry) ] <- NA

White_Native_img_undermined_cult <- ess_data %>%
  dplyr::filter(!is.na(White_Native_img_undermined_cult)) %>%
  dplyr::filter(no_pop_party!=1) %>%
  as_survey_design(weights = c(fullweight)) %>%
  dplyr::group_by(cntry) %>%
  dplyr::summarise(share_profile = survey_mean(White_Native_img_undermined_cult, na.rm = FALSE, vartype = "ci"))


White_Native_img_undermined_cult_pop <- ess_data %>%
  dplyr::filter(White_Native_img_undermined_cult==1) %>%
  dplyr::filter(no_pop_party!=1) %>%
  as_survey_design(weights = c(fullweight)) %>%
  dplyr::group_by(cntry) %>%
  dplyr::summarise(share_popvote = survey_mean(vote_choice_PopList_RightPop, na.rm = FALSE, vartype = "ci"))

White_Native_img_undermined_cult_pop_total <- merge(White_Native_img_undermined_cult,White_Native_img_undermined_cult_pop,by="cntry")

older55_authoritarian <- ess_data %>%
  dplyr::filter(!is.na(older55_authoritarian)) %>%
  dplyr::filter(no_pop_party!=1) %>%
  as_survey_design(weights = c(fullweight)) %>%
  dplyr::group_by(cntry) %>%
  dplyr::summarise(share_profile = survey_mean(older55_authoritarian, na.rm = FALSE, vartype = "ci"))

older55_authoritarian_cult_pop <- ess_data %>%
  dplyr::filter(older55_authoritarian==1) %>%
  dplyr::filter(no_pop_party!=1) %>%
  as_survey_design(weights = c(fullweight)) %>%
  dplyr::group_by(cntry) %>%
  dplyr::summarise(share_popvote = survey_mean(vote_choice_PopList_RightPop, na.rm = FALSE, vartype = "ci"))

older55_authoritarian_cult_pop_total <- merge(older55_authoritarian,older55_authoritarian_cult_pop,by="cntry")



rural_have_no_voice2 <- ess_data %>%
  dplyr::filter(!is.na(rural_have_no_voice2)) %>%
  dplyr::filter(no_pop_party!=1) %>%
  as_survey_design(weights = c(fullweight)) %>%
  dplyr::group_by(cntry) %>%
  dplyr::summarise(share_profile = survey_mean(rural_have_no_voice2, na.rm = FALSE, vartype = "ci"))

rural_have_no_voice2_cult_pop <- ess_data %>%
  dplyr::filter(rural_have_no_voice2==1) %>%
  dplyr::filter(no_pop_party!=1) %>%
  as_survey_design(weights = c(fullweight)) %>%
  dplyr::group_by(cntry) %>%
  dplyr::summarise(share_popvote = survey_mean(vote_choice_PopList_RightPop, na.rm = FALSE, vartype = "ci"))

rural_have_no_voice2_cult_pop_total <- merge(rural_have_no_voice2,rural_have_no_voice2_cult_pop,by="cntry")


social_status25_respect2 <- ess_data %>%
  dplyr::filter(!is.na(social_status25_respect2)) %>%
  dplyr::filter(no_pop_party!=1) %>%
  as_survey_design(weights = c(fullweight)) %>%
  dplyr::group_by(cntry) %>%
  dplyr::summarise(share_profile = survey_mean(social_status25_respect2, na.rm = FALSE, vartype = "ci"))


social_status25_respect2_cult_pop <- ess_data %>%
  dplyr::filter(social_status25_respect2==1) %>%
  dplyr::filter(no_pop_party!=1) %>%
  as_survey_design(weights = c(fullweight)) %>%
  dplyr::group_by(cntry) %>%
  dplyr::summarise(share_popvote = survey_mean(vote_choice_PopList_RightPop, na.rm = FALSE, vartype = "ci"))

social_status25_respect2_cult_pop_total <- merge(social_status25_respect2,social_status25_respect2_cult_pop,by="cntry")

distant_people_local__noturban <- ess_data %>%
  dplyr::filter(!is.na(distant_people_local_noturban)) %>%
  dplyr::filter(no_pop_party!=1) %>%
  as_survey_design(weights = c(fullweight)) %>%
  dplyr::group_by(cntry) %>%
  dplyr::summarise(share_profile = survey_mean(distant_people_local_noturban, na.rm = FALSE, vartype = "ci"))

distant_people_local__noturban_cult_pop <- ess_data %>%
  dplyr::filter(distant_people_local_noturban==1) %>%
  as_survey_design(weights = c(fullweight)) %>%
  dplyr::group_by(cntry) %>%
  dplyr::summarise(share_popvote = survey_mean(vote_choice_PopList_RightPop, na.rm = FALSE, vartype = "ci"))

distant_people_local_cult_pop_total <- merge(distant_people_local__noturban,distant_people_local__noturban_cult_pop,by="cntry")

culturalstories_bycntry <- bind_rows( White_Native_img_undermined_cult_pop_total,
                                      older55_authoritarian_cult_pop_total,
                                      rural_have_no_voice2_cult_pop_total,
                                      distant_people_local_cult_pop_total,
                                      social_status25_respect2_cult_pop_total,
                                      .id="Characteristic")

culturalstories_bycntry$Characteristic<-factor(culturalstories_bycntry$Characteristic, 
                                               levels=c(1,2,3,4,5),
                                               labels=c("Ethno-Cultural Estrangement",
                                                        "Intergenerational Backlash",
                                                        "Rural Resentment",
                                                        "Community Disintegration",
                                                        "Social Status Anxiety"))



culturalstories_bycntry<-tibble(culturalstories_bycntry)
culturalstories_bycntry2<-
  culturalstories_bycntry%>%
  mutate(share_profile_prec=share_profile*100)%>%
  mutate(share_profile_upp_prec=share_profile_upp*100)%>%
  mutate(share_popvote_amongprofile_prec=share_profile_prec*share_popvote)

culturalstories_bycntry_data<-
  culturalstories_bycntry2%>%
  dplyr::select(Characteristic, cntry, share_profile_prec, share_profile_upp_prec, share_popvote_amongprofile_prec)

pop_bycntry <- ess_data %>%
  dplyr::filter(!is.na(vote_choice_PopList_RightPop)) %>%
  dplyr::filter(no_pop_party!=1) %>%
  as_survey_design(weights = c(fullweight)) %>%
  dplyr::group_by(cntry) %>%
  dplyr::summarise(share_total_popvotre= survey_mean(vote_choice_PopList_RightPop, na.rm = FALSE, vartype = "ci")) %>%
  mutate(share_total_popvotre=share_total_popvotre*100)


data_figSI8 <- merge(culturalstories_bycntry_data,pop_bycntry,by="cntry")
data_figSI8<-as.tibble(data_figSI8)


Fig_SI8<-data_figSI8 %>%
  mutate(Characteristic = fct_reorder(Characteristic, desc(share_profile_prec))) %>%
  ggplot()+
  geom_col(aes(x=Characteristic,y=share_profile_prec),
           color="#97C1D1",fill="#97C1D1", width=0.7)+
  geom_errorbar(aes(x=Characteristic, ymin = share_profile_prec, 
                    ymax = share_profile_upp_prec), 
                width = 0.5, lwd=0.4, color="gray40") +
  geom_col(aes(x=Characteristic,y=share_popvote_amongprofile_prec),
           color="#A20021",fill="#A20021", width=0.7)+coord_flip()+
  geom_hline(aes(yintercept=share_total_popvotre),  linetype = 2, size=1, alpha=0.9, colour="#A20021")+
  labs(x = " ", y = "", 
       fill = "", color = "") +  
  theme_minimal() +facet_wrap(facets=~cntry,nrow=2, scales = "free_x")+
  scale_y_continuous(labels = function(x) paste0(x, "%"))+
  theme(legend.position = "bottom", legend.text = element_text(size=11),
        legend.margin = margin(t = -10, unit = "pt"), 
        strip.text.x = element_text(size = 13),
        axis.text = element_text(size = 13),
        axis.text.x = element_text(size = 10),
        plot.background = element_rect(fill = "white", colour = "white"),
        plot.margin = unit(c(0, 1, 0.5, 0), "cm"),
        panel.spacing = unit(0.5, "lines"))
Fig_SI8

ggsave(Fig_SI8, dpi = 600,
       filename = paste0(plotpath, "Fig_SI8.tif"), device = "tiff",
       height = 6, width = 12)


## ---------------------- Figure SI-9 Cultural Predictors of Voting for Right-Wing Populist Parties, by Country and Year, Unweighted Data -----------

coef_popvote_cultstories_bycntry2018unweighted <- ess_data %>%
  filter(Wave %in% c("2018")) %>%
  group_by(cntry)%>%
  do(tidy(lm(vote_choice_PopList_RightPop ~                
               White_Native_img_undermined_cult+
               older55_authoritarian+
               rural_have_no_voice2,
             data = .)))

coef_popvote_cultstories_bycntry2016unweighted <- ess_data %>%
  filter(Wave %in% c("2016")) %>%
  group_by(cntry)%>%
  do(tidy(lm(vote_choice_PopList_RightPop ~                
               White_Native_img_undermined_cult+
               older55_authoritarian+
               rural_have_no_voice2,
             data = .)))

coef_popvote_cultstories_bycntry2014unweighted <- ess_data %>%
  filter(Wave %in% c("2014")) %>%
  group_by(cntry)%>%
  do(tidy(lm(vote_choice_PopList_RightPop ~                
               White_Native_img_undermined_cult+
               older55_authoritarian+
               rural_have_no_voice2,
             data = .)))

coef_popvote_cultstories_bycntry2012unweighted <- ess_data %>%
  filter(Wave %in% c("2012")) %>%
  group_by(cntry)%>%
  do(tidy(lm(vote_choice_PopList_RightPop ~                
               White_Native_img_undermined_cult+
               older55_authoritarian+
               distant_people_local_noturban+
               social_status25_respect2,
             data = .)))


data_Fig_S9 <- bind_rows( coef_popvote_cultstories_bycntry2018unweighted,
                          coef_popvote_cultstories_bycntry2016unweighted,
                          coef_popvote_cultstories_bycntry2014unweighted,
                          coef_popvote_cultstories_bycntry2012unweighted,
                          .id="Wave")

data_Fig_S9$Wave<-factor(data_Fig_S9$Wave, 
                         levels=c(1,2,3,4),
                         labels=c("2018",
                                  "2016",
                                  "2014",
                                  "2012"))


data_Fig_S9<-data_Fig_S9%>% 
  filter(term %in% c("White_Native_img_undermined_cult", 
                     "older55_authoritarian", "rural_have_no_voice2",
                     "distant_people_local_noturban", "social_status25_respect2")) %>%
  mutate(term=case_when(
    term=="White_Native_img_undermined_cult"~"Ethno-Cultural Estrangement",
    term=="older55_authoritarian"~"Intergenerational Backlash",
    term=="rural_have_no_voice2"~"Rural Resentment",
    term=="social_status25_respect2"~"Social Status Anxiety",
    term=="distant_people_local_noturban"~"Community Disintegration"
  )) 

Fig_SI9<-
  data_Fig_S9 %>%  
  ggplot()+aes(term, estimate, fill=term, color=term, shape=Wave)+ 
  geom_hline(yintercept=0, linetype=2, lwd=0.9, size=1.3, colour = "#ACBBBF", alpha=0.9) +
  geom_errorbar(stat = "identity", alpha = 0.5, 
                position = position_dodge(width = 0.5),
                aes(ymin=estimate - 1.96*std.error, ymax=estimate + 1.96*std.error),
                lwd=1.2, width = 0)+
  geom_errorbar(stat = "identity", alpha = 0.8, 
                position = position_dodge(width = 0.5),
                aes(ymin=estimate - 1.64*std.error, ymax=estimate + 1.64*std.error), 
                lwd=1, width=0) +
  scale_colour_manual(values = c("#24416B","#2F7275","#80ABC6","#E84F5C","#96051A"))+
  scale_fill_manual(values = c("#24416B","#2F7275","#80ABC6","#E84F5C","#96051A"))+
  geom_point(stat = "identity", alpha = 0.7,  
             size = 1.8, position = position_dodge(width = 0.5)) + 
  guides(color = FALSE, fill = FALSE)+
  coord_flip() + 
  labs(x = "", y = " ", subtitle = "", shape="") +
  facet_wrap(facets=~cntry,nrow=2)+
  theme_minimal() +theme(legend.position = "bottom", legend.text = element_text(size=11),
                         legend.margin = margin(t = -10, unit = "pt"), 
                         strip.text.x = element_text(size = 13),
                         axis.text = element_text(size = 13),
                         axis.text.x = element_text(size = 10),
                         plot.background = element_rect(fill = "white", colour = "white"),
                         plot.margin = unit(c(0, 1, 0.5, 0), "cm"),
                         panel.spacing = unit(0.5, "lines"))

Fig_SI9

ggsave(Fig_SI9, dpi = 600,
       filename = paste0(plotpath, "Fig_SI9.tif"), device = "tiff",
       height = 6, width = 12)


## ---------------------- Figure SI-10 Matching a cultural vs economic proﬁle and the probability to vote for Populist Parties------

ess_data_sumcult<-ess_data %>%
  dplyr::select(idno, Wave, cntry, fullweight, vote_choice_PopList_RightPop, vote_RightPop_factor, White_Native_img_undermined_cult, 
                older55_authoritarian, rural_have_no_voice2, social_status25_respect2, distant_people_local_noturban,
                unemployed_lookingforjob, production_worker, below_2median_income, difficult_subj )

ess_data_sumcult<-ess_data_sumcult %>%
  rowwise() %>%
  mutate(sum_stories_cult = sum(White_Native_img_undermined_cult, 
                                older55_authoritarian, 
                                rural_have_no_voice2,
                                social_status25_respect2, distant_people_local_noturban, na.rm = TRUE))

ess_data_sumcult$culturalconcern<- as.numeric (with(ess_data_sumcult, ifelse ((sum_stories_cult!=0),1,0)))
ess_data_sumcult$culturalconcern[is.na(ess_data_sumcult$sum_stories_cult) ] <- NA

data_Fig_SI10_sumcult<-ess_data_sumcult %>%
  rowwise() %>%
  mutate(sum_stories_econ= sum(difficult_subj, 
                               below_2median_income, 
                               production_worker,
                               unemployed_lookingforjob, na.rm = TRUE))
data_Fig_SI10_sumcult$economicisequrity<- as.numeric (with(data_Fig_SI10_sumcult, ifelse ((sum_stories_econ!=0),1,0)))
data_Fig_SI10_sumcult$economicisequrity[is.na(data_Fig_SI10_sumcult$sum_stories_econ) ] <- NA

data_Fig_SI10_sumcult<-data_Fig_SI10_sumcult %>%
  mutate(cult_econ=case_when(economicisequrity==1 & culturalconcern==1 ~"Economic & Cultural concerns",
                             economicisequrity==1 & culturalconcern==0 ~"Economic concern",
                             economicisequrity==0 & culturalconcern==1 ~"Cultural concern",
                             economicisequrity==0 & culturalconcern==0 ~"Neither" ))

data_Fig_SI10_sumcult$cult_econ<-factor(data_Fig_SI10_sumcult$cult_econ, 
                                        levels=c(       "Neither",
                                                        "Economic concern",
                                                        "Economic & Cultural concerns",
                                                        "Cultural concern" ))


data_Fig_SI10_sumcult$economic_con<- as.numeric (with(data_Fig_SI10_sumcult, 
                                                      ifelse ((cult_econ=="Economic concern"),1,0)))
data_Fig_SI10_sumcult$economic_con[is.na(data_Fig_SI10_sumcult$cult_econ) ] <- NA

data_Fig_SI10 <- data_Fig_SI10_sumcult %>%
  filter(Wave %in% c("2012","2014","2016", "2018")) %>%
  group_by(cntry)%>%
  do(tidy(lm(vote_choice_PopList_RightPop ~                
               cult_econ+factor(Wave),
             weights = fullweight, data = .)))

data_Fig_SI10<-data_Fig_SI10%>% 
  filter(term == "cult_econEconomic concern" |
           term == "cult_econEconomic & Cultural concerns" |
           term == "cult_econCultural concern"  )

data_Fig_SI10<-data_Fig_SI10%>% 
  mutate(term=case_when(
    term=="cult_econEconomic concern"~"Economic concerns",
    term=="cult_econEconomic & Cultural concerns"~"Both Economic & Cultural",
    term=="cult_econCultural concern"~"Cultural concerns"
  )) 
data_Fig_SI10$term2<-factor(data_Fig_SI10$term)


Fig_SI10<-
  data_Fig_SI10 %>%  
  ggplot()+aes(cntry, estimate, fill=term2, colour=term2)+ 
  geom_hline(yintercept=0, linetype=2, lwd=0.9, size=1.3, colour = "#ACBBBF", alpha=0.9) +
  geom_errorbar(stat = "identity", alpha = 0.5, 
                position = position_dodge(width = 0.5),
                aes(ymin=estimate - 1.96*std.error, ymax=estimate + 1.96*std.error),
                lwd=1.2, width = 0)+
  geom_errorbar(stat = "identity", alpha = 0.95, 
                position = position_dodge(width = 0.5),
                aes(ymin=estimate - 1.64*std.error, ymax=estimate + 1.64*std.error), 
                lwd=1, width=0) +
  geom_point(stat = "identity", alpha = 0.7,  
             size = 1.8, position = position_dodge(width = 0.5)) + 
  scale_fill_manual(values = c("#805252", "#2F918E" , "#B09B27"))+
  scale_colour_manual(values =  c("#805252", "#2F918E" , "#B09B27"))+
  facet_wrap(facets=~cntry,ncol=1, scale="free_y")+
  coord_flip() + 
  labs(y = " ", 
       x = "  ", subtitle = "", shape="", fill="", colour="") +
  theme_minimal() + theme(legend.position = "bottom",         
                          legend.box = "vertical", 
                          plot.background = element_rect(fill = "white", colour = "white"),
                          strip.text.x = element_text(size = 0),
                          text = element_text(size=13))
Fig_SI10

ggsave(Fig_SI10, dpi = 600,
       filename = paste0(plotpath, "Fig_SI10.tif"), device = "tiff",
       height = 6.5, width = 6.5)


## ---------------------- Table  SI-11 Interaction between cultural accounts and economic concerns  ------
ess_data$less_turst<- as.numeric (with(ess_data, ifelse ((ess_data$trstprl<5),1,0))) 
ess_data$rural_resentment_trust<- as.numeric (with(ess_data, ifelse ((ess_data$Rural_area==1 & 
                                                                        ess_data$less_turst==1),1,0)))
ess_data$rural_resentment_trust[is.na(ess_data$less_turst) |  is.na(ess_data$Rural_area) ] <- NA



pulled_2012_int_ethno<-lm(vote_choice_PopList_RightPop ~                
                            White_Native_img_undermined_cult+
                            older55_authoritarian+
                            distant_people_local_noturban+
                            social_status25_respect2+
                            rural_resentment_trust+
                            economicisequrity+
                            White_Native_img_undermined_cult*economicisequrity+
                            factor(cntry), weights = fullweight,    
                          data=subset(ess_data,Wave=="2012"))

pulled_2012_int_integen<-lm(vote_choice_PopList_RightPop ~                
                              White_Native_img_undermined_cult+
                              older55_authoritarian+
                              distant_people_local_noturban+
                              social_status25_respect2+
                              rural_resentment_trust+
                              economicisequrity+
                              older55_authoritarian*economicisequrity+
                              factor(cntry), weights = fullweight,    
                            data=subset(ess_data,Wave=="2012"))
pulled_2012_int_commun<-lm(vote_choice_PopList_RightPop ~                
                             White_Native_img_undermined_cult+
                             older55_authoritarian+
                             distant_people_local_noturban+
                             social_status25_respect2+
                             rural_resentment_trust+
                             economicisequrity+
                             distant_people_local_noturban*economicisequrity+
                             factor(cntry), weights = fullweight,    
                           data=subset(ess_data,Wave=="2012"))
pulled_2012_int_status<-lm(vote_choice_PopList_RightPop ~                
                             White_Native_img_undermined_cult+
                             older55_authoritarian+
                             distant_people_local_noturban+
                             social_status25_respect2+
                             rural_resentment_trust+
                             economicisequrity+
                             social_status25_respect2*economicisequrity+
                             factor(cntry), weights = fullweight,    
                           data=subset(ess_data,Wave=="2012"))
pulled_2012_int_rural<-lm(vote_choice_PopList_RightPop ~                
                            White_Native_img_undermined_cult+
                            older55_authoritarian+
                            distant_people_local_noturban+
                            social_status25_respect2+
                            rural_resentment_trust+
                            economicisequrity+
                            rural_resentment_trust*economicisequrity+
                            factor(cntry), weights = fullweight,    
                          data=subset(ess_data,Wave=="2012"))

pulled_2012_int_all<-lm(vote_choice_PopList_RightPop ~                
                          White_Native_img_undermined_cult+
                          older55_authoritarian+
                          distant_people_local_noturban+
                          social_status25_respect2+
                          rural_resentment_trust+
                          economicisequrity+
                          White_Native_img_undermined_cult*economicisequrity+
                          older55_authoritarian*economicisequrity+
                          distant_people_local_noturban*economicisequrity+
                          social_status25_respect2*economicisequrity+
                          rural_resentment_trust*economicisequrity+
                          factor(cntry), weights = fullweight,    
                        data=subset(ess_data,Wave=="2012"))
stargazer(
  pulled_2012_int_ethno, pulled_2012_int_integen,  pulled_2012_int_commun,  
  pulled_2012_int_status, pulled_2012_int_rural,pulled_2012_int_all,
  type = "text", 
  keep=c("older55_authoritarian",
         "White_Native_img_undermined_cult",
         "rural_resentment_trust",
         "distant_people_local_noturban",
         "social_status25_respect2",
         "economicisequrity",
         "older55_authoritarian:economicisequrity",
         "White_Native_img_undermined_cult:economicisequrity",
         "rural_resentment_trust:economicisequrity",
         "distant_people_local_noturban:economicisequrity",
         "social_status25_respect2:economicisequrity", "Constant"),
  covariate.labels=c("Ethno-Cult Estrangement",
                     "Intergen Backlash",
                     "Community Disintegration",
                     "Social Status Anxiety",
                     "Rural Resentment",
                     "Economic Insecurity",
                     "Ethno-Cult x Econ Insec",
                     "Intergen Backlash x Econ Insec",
                     "Community Dis x Econ Insec",
                     "Status Anxiety  x Econ Insec",
                     "Rural Resentment x Econ Insec"),
  dep.var.labels=c("Voting for Populist Parties"),
  title="Interaction between cultural and economic concerns, by country - 2012",
  omit.stat = c('adj.rsq', 'ser', 'f'),
  star.cutoffs = c(0.05, 0.01, 0.001), star.char = c('*','**','**'),
  notes = '*p<0.05; **p<0.01', notes.append = F, no.space=TRUE,  align=TRUE)


## ---------------------- Figure SI-11 Age cohorts and right-wing populist support -------




calculate_mean <- function(var, data) {
  var_name <- as.name(var)
  data %>%
    dplyr::filter(!is.na(!!var_name)) %>%
    as_survey_design(weights = c(fullweight)) %>%
    dplyr::group_by(cntry,vote_RightPop_factor) %>%
    dplyr::summarize(n = survey_mean(!!var_name, na.rm = FALSE, vartype = "ci"))
}

older55_pop <- calculate_mean("older55", ess_data)
older65_pop <- calculate_mean("older65", ess_data)
Interwar_cohort_pop <- calculate_mean("Interwar_cohort", ess_data)
BabyBoomers_cohort_pop <- calculate_mean("BabyBoomers_cohort", ess_data)
GenX_cohort_pop <- calculate_mean("GenX_cohort", ess_data)


data_SI11 <- bind_rows(older55_pop, 
                                             older65_pop,
                                             Interwar_cohort_pop,
                                             BabyBoomers_cohort_pop,
                                             GenX_cohort_pop,
                                             .id="Characteristic")
data_SI11$Characteristic<-factor(data_SI11$Characteristic, levels=c(1,2,3,4,5),
                                                       labels=c("*Older (55+)",
                                                                "Older (65+)",
                                                                "Interwar",
                                                                "Baby Boomers",
                                                                "Gen X"))
data_SI11$vote_RightPop_factor<-factor(data_SI11$vote_RightPop_factor)
data_SI11$vote_RightPop_factor <- relevel(data_SI11$vote_RightPop_factor, 
                                                       ref = "Right Wing Populist Parties")

Fig_SI11<-data_SI11 %>%
  mutate(Characteristic = fct_reorder(Characteristic, desc(n))) %>%
  ggplot()+aes(x=Characteristic,y=n,label=n,fill=vote_RightPop_factor,colour=vote_RightPop_factor)+
  geom_col(alpha=0.9,width=0.5, position = position_dodge(width=0.7))+
  geom_errorbar(aes(ymin = n, 
                    ymax = n_upp), position = position_dodge(width=0.7),
                width = 0.5, lwd=0.4, color="gray40") +
  scale_fill_manual(values = c("#A20021", "#97C1D1"))+
  scale_colour_manual(values = c("#A20021", "#97C1D1"))+
  scale_y_continuous(labels=scales::percent) +
  labs(x = " ", y = "", subtitle = "", title="", 
       fill = "", color = "") +  coord_flip()+
  theme_minimal() +facet_wrap(facets=~cntry,nrow=2)+
  theme(legend.position = "bottom",  
        strip.text.x = element_text(size = 14),
        axis.text = element_text(size = 14),
        plot.background = element_rect(fill = "white", colour = "white"),
        panel.spacing = unit(1.6, "lines"))
Fig_SI11


ggsave(Fig_SI11, dpi = 600,
       filename = paste0(plotpath, "Fig_SI11.tif"), device = "tiff",
       height = 11, width = 11)




## ---------------------- Table  SI-15 Principal Component Analysis-------
df <- data.frame(ess_data$ipfrule, 
                 ess_data$impsafe, 
                 ess_data$ipbhprp, 
                 ess_data$ipstrgv, 
                 ess_data$imptrad)

df.scaled <- as.data.frame(scale(df, center = TRUE, scale = TRUE))
aff.pc <- principal(df, nfactors = 1, rotate = "varimax", scores = T)
aff.pc
summary(aff.pc)
ess_data$authoritarian_pcaindex <- aff.pc$scores[,1]
summary(ess_data$authoritarian_pcaindex )


#Median  -0.1067
ess_data$older55_authoritarian<- as.numeric (with(ess_data, ifelse ((older55==1 &  authoritarian==1),1,0)))

ess_data$authoit_values_Medianpca<- as.numeric(with(ess_data, 
                                                    ifelse ((authoritarian_pcaindex<(-0.1067)),1,0))) 

#1st Qu.  -0.7862
ess_data$authoit_values_1rdpca<- as.numeric(with(ess_data, 
                                                 ifelse ((authoritarian_pcaindex<(-0.7862)),1,0))) 

ess_data$older55_authoritarianPCA1<- as.numeric (with(ess_data, ifelse ((older55==1 &  authoit_values_1rdpca==1),1,0)))


## ---------------------- Figure SI-12 The inter-generational divide in voting, using alternative measures-------

older55_authoritarianPCA1_pop <- ess_data %>%
  dplyr::filter(!is.na(older55_authoritarianPCA1)) %>%
  filter(Wave %in% c("2012","2014","2016", "2018")) %>%
  as_survey_design(weights = c(fullweight)) %>%
  dplyr::group_by(cntry,  vote_RightPop_factor) %>%
  dplyr::summarize(n = survey_mean(older55_authoritarianPCA1, na.rm = FALSE, vartype = "ci")) 

ess_data$older55_authoit_values_Medianpca<- as.numeric (with(ess_data, ifelse ((older55==1 &  authoit_values_Medianpca==1),1,0)))

older55_authoit_values_Medianpca_pop <- ess_data %>%
  dplyr::filter(!is.na(older55_authoit_values_Medianpca)) %>%
  filter(Wave %in% c("2012","2014","2016", "2018")) %>%
  as_survey_design(weights = c(fullweight)) %>%
  dplyr::group_by(cntry,  vote_RightPop_factor) %>%
  dplyr::summarize(n = survey_mean(older55_authoit_values_Medianpca, na.rm = FALSE, vartype = "ci")) 


ess_data$older65_authoritarian<- as.numeric (with(ess_data, ifelse ((older65==1 &  
                                                                       authoritarian==1),1,0)))
older65_authoritarian_pop <- ess_data %>%
  dplyr::filter(!is.na(older65_authoritarian)) %>%
  filter(Wave %in% c("2012","2014","2016", "2018")) %>%
  as_survey_design(weights = c(fullweight)) %>%
  dplyr::group_by(cntry,  vote_RightPop_factor) %>%
  dplyr::summarize(n = survey_mean(older65_authoritarian, na.rm = FALSE, vartype = "ci")) 

ess_data$born_bef1945_authoritarian<- as.numeric (with(ess_data, ifelse ((Interwar_cohort==1 &  
                                                                            authoritarian==1),1,0)))

born_bef1945_authoritarian_pop <- ess_data %>%
  dplyr::filter(!is.na(born_bef1945_authoritarian)) %>%
  filter(Wave %in% c("2012","2014","2016", "2018")) %>%
  as_survey_design(weights = c(fullweight)) %>%
  dplyr::group_by(cntry,  vote_RightPop_factor) %>%
  dplyr::summarize(n = survey_mean(born_bef1945_authoritarian, na.rm = FALSE, vartype = "ci")) %>%
  filter(!is.na( vote_RightPop_factor)) 


older55_authoritarian_pop <- ess_data %>%
  dplyr::filter(!is.na(older55_authoritarian)) %>%
  as_survey_design(weights = c(fullweight)) %>%
  dplyr::group_by(cntry,  vote_RightPop_factor) %>%
  dplyr::summarize(n = survey_mean(older55_authoritarian, na.rm = FALSE, vartype = "ci")) 


data_SI12 <- bind_rows(born_bef1945_authoritarian_pop,
                                       older55_authoritarian_pop,
                                       older65_authoritarian_pop,
                                       older55_authoritarianPCA1_pop,
                                       .id="Characteristic")
data_SI12$Characteristic<-factor(data_SI12$Characteristic, levels=c(1,2,3,4),
                                                 labels=c("Born before 1945 & auth values",
                                                          "*Older (55+) & auth values",
                                                          "Older (65+) & auth values",
                                                          "Older (55+) & auth PCA (1st Qu.)" ))
data_SI12$vote_RightPop_factor<-factor(data_SI12$vote_RightPop_factor)
data_SI12$vote_RightPop_factor <- relevel(data_SI12$vote_RightPop_factor, ref = "Right Wing Populist Parties")

Fig_SI12<-data_SI12 %>%
  mutate(Characteristic = fct_reorder(Characteristic, desc(n))) %>%
  ggplot()+aes(x=Characteristic,y=n,label=n,fill= vote_RightPop_factor,colour= vote_RightPop_factor)+
  geom_col(alpha=0.9,width=0.5, position = position_dodge(width=0.7))+
  geom_errorbar(aes(ymin = n, 
                    ymax = n_upp), position = position_dodge(width=0.7),
                width = 0.5, lwd=0.4, color="gray40") +
  scale_fill_manual(values = c("#A20021", "#97C1D1"))+
  scale_colour_manual(values = c("#A20021", "#97C1D1"))+
  scale_y_continuous(labels=scales::percent) +
  labs(x = " ", y = "", subtitle = "", title="", 
       fill = "", color = "") +  coord_flip()+
  theme_minimal() +facet_wrap(facets=~cntry,nrow=2)+
  theme(legend.position = "bottom",  
        text = element_text(size = 13),
        strip.text.x = element_text(size = 14),
        axis.text.y = element_text(size = 11),
        axis.text.x = element_text(size = 10),
        plot.background = element_rect(fill = "white", colour = "white"),
        plot.margin = unit(c(-1.3, 1, 0.5, 0), "cm"),
        panel.spacing = unit(0.5, "lines"))
Fig_SI12

ggsave(Fig_SI12, dpi = 600,
       filename = paste0(plotpath, "Fig_SI12.tif"), device = "tiff",
       height = 6, width = 12)

## ---------------------- Figure SI-13 Ethno-cultural estrangement among populist versus non-populist voters, alternative indicators ------
# Undermined cultural
White_Native_img_undermined_cult_pop <- ess_data %>%
  dplyr::filter(!is.na(White_Native_img_undermined_cult)) %>%
  as_survey_design(weights = c(fullweight)) %>%
  dplyr::group_by(cntry,  vote_RightPop_factor) %>%
  dplyr::summarize(n = survey_mean(White_Native_img_undermined_cult, na.rm = FALSE, vartype = "ci")) %>%
  filter(!is.na( vote_RightPop_factor)) 


# Immigrants from the same ethnic group - immigrants from different ethnic group
# (1 Allow many to come and live here,  Allow none, 3 Allow a few, 4 Allow none)
ess_data$White_Native_allowimmig_sameVSdiffethnic<- as.numeric (with(ess_data, 
                                                                     ifelse ((born_incountry==1 & 
                                                                                ethnic_minority==0 & 
                                                                                allowimmig_sameVSdiffethnic_d==1),1,0)))
ess_data$White_Native_allowimmig_sameVSdiffethnic[is.na(ess_data$born_incountry) |
                                                    is.na(ess_data$ethnic_minority)|
                                                    is.na(ess_data$allowimmig_sameVSdiffethnic_d)] <- NA

White_Native_allowimmig_sameVSdiffethnic_pop <- ess_data %>%
  dplyr::filter(!is.na(White_Native_allowimmig_sameVSdiffethnic)) %>%
  filter(Wave %in% c("2012","2014","2016", "2018")) %>%
  as_survey_design(weights = c(fullweight)) %>%
  dplyr::group_by(cntry,  vote_RightPop_factor) %>%
  dplyr::summarize(n = survey_mean(White_Native_allowimmig_sameVSdiffethnic, na.rm = FALSE, vartype = "ci")) %>%
  filter(!is.na( vote_RightPop_factor)) 

# Of every 100 people in country how many born outside country
ess_data<-ess_data %>%
  mutate(foreignborn_share= case_when(cntry=="Switzerland" & Wave=="2012"~ 27,
                                      cntry=="Switzerland" & Wave=="2014"~ 27.9,
                                      cntry=="Switzerland" & Wave=="2016"~ 28.8,
                                      cntry=="Switzerland" & Wave=="2018"~ 29.5,
                                      cntry=="Germany" & Wave=="2012"~ 12.1,
                                      cntry=="Germany" & Wave=="2014"~ 12.8,
                                      cntry=="Germany" & Wave=="2016"~ 13.9,
                                      cntry=="Germany" & Wave=="2018"~ 15.8,
                                      cntry=="Denmark" & Wave=="2012"~ 7.9,
                                      cntry=="Denmark" & Wave=="2014"~ 8.4,
                                      cntry=="Denmark" & Wave=="2016"~ 9.5,
                                      cntry=="Denmark" & Wave=="2018"~ 10.3,
                                      cntry=="France" & Wave=="2012"~ 11.8,
                                      cntry=="France" & Wave=="2014"~ 12,
                                      cntry=="France" & Wave=="2016"~ 12.3,
                                      cntry=="France" & Wave=="2018"~ 12.5,
                                      cntry=="United Kingdom" & Wave=="2012"~ 11.8,
                                      cntry=="United Kingdom" & Wave=="2014"~ 12.3,
                                      cntry=="United Kingdom" & Wave=="2016"~ 13.6,
                                      cntry=="United Kingdom" & Wave=="2018"~ 13.7,
                                      cntry=="Hungary" & Wave=="2012"~ 4.1,
                                      cntry=="Hungary" & Wave=="2014"~ 4.6,
                                      cntry=="Hungary" & Wave=="2016"~ 5.2,
                                      cntry=="Hungary" & Wave=="2018"~ 5.5,
                                      cntry=="Italy" & Wave=="2012"~ 9.5,
                                      cntry=="Italy" & Wave=="2014"~ 9.5,
                                      cntry=="Italy" & Wave=="2016"~ 9.7,
                                      cntry=="Italy" & Wave=="2018"~ 10.2,
                                      cntry=="Netherlands" & Wave=="2012"~ 11.4,
                                      cntry=="Netherlands" & Wave=="2014"~ 11.6,
                                      cntry=="Netherlands" & Wave=="2016"~ 12.1,
                                      cntry=="Netherlands" & Wave=="2018"~ 13,
                                      cntry=="Poland" & Wave=="2012"~ 1.6,
                                      cntry=="Poland" & Wave=="2014"~ 1.6,
                                      cntry=="Poland" & Wave=="2016"~ 1.6,
                                      cntry=="Poland" & Wave=="2018"~ 1.8,
                                      cntry=="Sweden" & Wave=="2012"~ 15,
                                      cntry=="Sweden" & Wave=="2014"~ 15.8,
                                      cntry=="Sweden" & Wave=="2016"~ 17,
                                      cntry=="Sweden" & Wave=="2018"~ 18.8,))

ess_data<-ess_data %>%
  mutate(per20_immigrants= foreignborn_share*2)

ess_data$noimbro[ess_data$noimbro > 100] <- NA 
ess_data$morethan20per_immigrants<- as.numeric (with(ess_data, 
                                                     ifelse ((ess_data$noimbro>per20_immigrants),1,0)))
ess_data$morethan20per_immigrants[is.na(ess_data$noimbro)  ] <- NA


ess_data$White_Native_imorethan20per_immigrants<- as.numeric (with(ess_data, 
                                                                   ifelse ((born_incountry==1 & 
                                                                              ethnic_minority==0 & 
                                                                              morethan20per_immigrants==1),1,0)))
ess_data$White_Native_imorethan20per_immigrants[is.na(ess_data$born_incountry) |
                                                  is.na(ess_data$ethnic_minority)|
                                                  is.na(ess_data$morethan20per_immigrants)] <- NA


White_Native_imorethan20per_immigrants_pop <- ess_data %>%
  dplyr::filter(!is.na(White_Native_imorethan20per_immigrants)) %>%
  filter(Wave %in% c("2012","2014","2016", "2018")) %>%
  as_survey_design(weights = c(fullweight)) %>%
  dplyr::group_by(cntry,  vote_RightPop_factor) %>%
  dplyr::summarize(n = survey_mean(White_Native_imorethan20per_immigrants, na.rm = FALSE, vartype = "ci")) %>%
  filter(!is.na( vote_RightPop_factor)) 

# Figure
data_SI13 <- bind_rows( White_Native_allowimmig_sameVSdiffethnic_pop,
                                      White_Native_imorethan20per_immigrants_pop,
                                      White_Native_img_undermined_cult_pop,
                                      .id="Characteristic")

data_SI13$Characteristic<-factor(data_SI13$Characteristic, 
                                               levels=c(1,2,3),
                                               labels=c("Sensitivity to immig of different group",
                                                        "Misperceptions of immig levels (more than 200%)",
                                                        "*Country's cultural life undermined by immig" ))

data_SI13$vote_RightPop_factor<-factor(data_SI13$vote_RightPop_factor)
data_SI13$vote_RightPop_factor <- relevel(data_SI13$vote_RightPop_factor, ref = "Right Wing Populist Parties")
Fig_SI13<-data_SI13 %>%
  mutate(Characteristic = fct_reorder(Characteristic, desc(n))) %>%
  ggplot()+aes(x=Characteristic,y=n,label=n,fill= vote_RightPop_factor,colour= vote_RightPop_factor)+
  geom_col(alpha=0.9,width=0.5, position = position_dodge(width=0.7))+
  geom_errorbar(aes(ymin = n, 
                    ymax = n_upp), position = position_dodge(width=0.7),
                width = 0.5, lwd=0.4, color="gray40") +
  scale_fill_manual(values = c("#A20021", "#97C1D1"))+
  scale_colour_manual(values = c("#A20021", "#97C1D1"))+
  scale_y_continuous(labels=scales::percent) +
  labs(x = " ", y = "", subtitle = "", title="", 
       fill = "", color = "") +  coord_flip()+
  theme_minimal() +facet_wrap(facets=~cntry,nrow=2)+
  theme(legend.position = "bottom",  
        text = element_text(size = 13),
        strip.text.x = element_text(size = 14),
        axis.text.y = element_text(size = 11),
        axis.text.x = element_text(size = 10),
        plot.background = element_rect(fill = "white", colour = "white"),
        plot.margin = unit(c(0, 1, 0.5, 0), "cm"),
        panel.spacing = unit(1, "lines"))
Fig_SI13


ggsave(Fig_SI13, dpi = 600,
       filename = paste0(plotpath, "Fig_SI13.tif"), device = "tiff",
       height = 6, width = 12)
## ---------------------- Figure SI-14 Social status anxiety among populist versus non-populist voters, alternative indicators -------
ess_data$social_status25<- as.numeric (with(ess_data, ifelse ((plinsoc>1 & plinsoc<6),1,0))) 
ess_data$social_status25[is.na(ess_data$plinsoc) ] <- NA


social_social_status25_pop <- ess_data %>%
  dplyr::filter(!is.na(social_status25)) %>%
  filter(Wave %in% c("2012","2014","2016", "2018")) %>%
  as_survey_design(weights = c(fullweight)) %>%
  dplyr::group_by(cntry,  vote_RightPop_factor) %>%
  dplyr::summarize(n = survey_mean(social_status25, na.rm = FALSE, vartype = "ci")) 


ess_data$social_status24<- as.numeric (with(ess_data, ifelse ((plinsoc>1 & plinsoc<5),1,0))) 
ess_data$social_status24[is.na(ess_data$plinsoc) ] <- NA

social_social_status24_pop <- ess_data %>%
  dplyr::filter(!is.na(social_status24)) %>%
  filter(Wave %in% c("2012","2014","2016", "2018")) %>%
  as_survey_design(weights = c(fullweight)) %>%
  dplyr::group_by(cntry,  vote_RightPop_factor) %>%
  dplyr::summarize(n = survey_mean(social_status24, na.rm = FALSE, vartype = "ci")) 

# Original indicator used in the main analyis
# social_status25_respect2
social_status25_respect2_pop <- ess_data %>%
  dplyr::filter(!is.na(social_status25_respect2)) %>%
  filter(Wave %in% c("2012","2014","2016", "2018")) %>%
  as_survey_design(weights = c(fullweight)) %>%
  dplyr::group_by(cntry,  vote_RightPop_factor) %>%
  dplyr::summarize(n = survey_mean(social_status25_respect2, na.rm = FALSE, vartype = "ci")) 


# Social_status 2- 4  and imp. to get respect 2
ess_data$social_status24_respect2<- as.numeric (with(ess_data, ifelse ((social_status24==1 &
                                                                          imp_getrespect2==1),1,0))) 
ess_data$social_status24_respect2[is.na(ess_data$social_status24) | is.na(ess_data$imp_getrespect2) ] <- NA


social_status24_respect2_pop <- ess_data %>%
  dplyr::filter(!is.na(social_status24_respect2)) %>%
  filter(Wave %in% c("2012","2014","2016", "2018")) %>%
  as_survey_design(weights = c(fullweight)) %>%
  dplyr::group_by(cntry,  vote_RightPop_factor) %>%
  dplyr::summarize(n = survey_mean(social_status24_respect2, na.rm = FALSE, vartype = "ci")) 

# Original indicator used in the main analyis only male
ess_data$social_status25_respect2_male<- as.numeric (with(ess_data, ifelse ((Male==1 &  
                                                                               social_status25==1 &
                                                                               imp_getrespect2==1),1,0))) 

ess_data$social_status25_respect2_male[is.na(ess_data$Male) | 
                                         is.na(ess_data$social_status25) | 
                                         is.na(ess_data$imp_getrespect2)] <- NA




table(ess_data$social_status25_respect2_male, ess_data$cntry)

social_status25_respect2_male_pop <- ess_data %>%
  dplyr::filter(!is.na(social_status25_respect2_male)) %>%
  filter(Wave %in% c("2012","2014","2016", "2018")) %>%
  as_survey_design(weights = c(fullweight)) %>%
  dplyr::group_by(cntry,  vote_RightPop_factor) %>%
  dplyr::summarize(n = survey_mean(social_status25_respect2_male, na.rm = FALSE, vartype = "ci")) 

# Figure
data_SI14 <- bind_rows( social_social_status25_pop,
                                     social_status24_respect2_pop,
                                     social_status25_respect2_male_pop,
                                     social_status25_respect2_pop,
                                     .id="Characteristic")
data_SI14$Characteristic<-factor(data_SI14$Characteristic, 
                                              levels=c(1,2,3,4),
                                              labels=c( 
                                                "Low Social Status (2-5)",
                                                "Low SS (2-4) & imp to get respect",
                                                "Low SS (2-5) & imp to get respect (male)",
                                                "*Low SS (2-5) & imp to get respect"
                                              ))


data_SI14$vote_RightPop_factor<-factor(data_SI14$vote_RightPop_factor)
data_SI14$vote_RightPop_factor <- relevel(data_SI14$vote_RightPop_factor, ref = "Right Wing Populist Parties")

Fig_SI14<-data_SI14 %>%
  filter(cntry!="United Kingdom")%>%
  filter(cntry!="Germany")%>%
  ggplot()+aes(x=Characteristic,y=n,label=n,fill= vote_RightPop_factor,colour= vote_RightPop_factor)+
  geom_col(alpha=0.9,width=0.5, position = position_dodge(width=0.7))+
  geom_errorbar(aes(ymin = n, 
                    ymax = n_upp), position = position_dodge(width=0.7),
                width = 0.5, lwd=0.4, color="gray40") +
  scale_fill_manual(values = c("#A20021", "#97C1D1"))+
  scale_colour_manual(values = c("#A20021", "#97C1D1"))+
  scale_y_continuous(labels=scales::percent) +
  labs(x = " ", y = "", subtitle = "", title="", 
       fill = "", color = "") +  coord_flip()+
  theme_minimal() +facet_wrap(facets=~cntry,nrow=2)+
  theme(legend.position = "bottom",  
        text = element_text(size = 13),
        axis.text.x = element_text(size = 10),
        axis.text.y = element_text(size = 11),
        plot.background = element_rect(fill = "white", colour = "white"),
        plot.margin = unit(c(0, 1, 0.5, 0), "cm"),
        panel.spacing = unit(1, "lines"))
Fig_SI14

ggsave(Fig_SI14, dpi = 600,
       filename = paste0(plotpath, "Fig_SI14.tif"), device = "tiff",
       height = 6, width = 12)

## ---------------------- Figure SI-15 Rural resentment and community disintegration among populist versus non- populist voters, alternative indicators -----

ess_data$rural_have_no_influence<- as.numeric (with(ess_data, ifelse ((Rural_area==1 &
                                                                         have_no_influence==1),1,0))) 

ess_data$rural_have_no_influence[is.na(ess_data$Rural_area) | 
                                   is.na(ess_data$have_no_influence) ] <- NA

rural_have_no_influence_pop <- ess_data %>%
  dplyr::filter(!is.na(rural_have_no_influence)) %>%
  filter(Wave %in% c("2012","2014","2016", "2018")) %>%
  as_survey_design(weights = c(fullweight)) %>%
  dplyr::group_by(cntry,  vote_RightPop_factor) %>%
  dplyr::summarize(n = survey_mean(rural_have_no_influence, na.rm = FALSE, vartype = "ci")) 



distant_people_local_pop <- ess_data %>%
  dplyr::filter(!is.na(distant_people_local)) %>%
  filter(Wave %in% c("2012","2014","2016", "2018")) %>%
  as_survey_design(weights = c(fullweight)) %>%
  dplyr::group_by(cntry,  vote_RightPop_factor) %>%
  dplyr::summarize(n = survey_mean(distant_people_local, na.rm = FALSE, vartype = "ci")) %>%
  filter(!is.na( vote_RightPop_factor)) 

rural_have_no_voice2_pop <- ess_data %>%
  dplyr::filter(!is.na(rural_have_no_voice2)) %>%
  as_survey_design(weights = c(fullweight)) %>%
  dplyr::group_by(cntry,  vote_RightPop_factor) %>%
  dplyr::summarize(n = survey_mean(rural_have_no_voice2, na.rm = FALSE, vartype = "ci")) 


distant_people_local__noturban_pop <- ess_data %>%
  dplyr::filter(!is.na(distant_people_local_noturban)) %>%
  as_survey_design(weights = c(fullweight)) %>%
  dplyr::group_by(cntry,  vote_RightPop_factor) %>%
  dplyr::summarize(n = survey_mean(distant_people_local_noturban, na.rm = FALSE, vartype = "ci")) %>%
  filter(!is.na( vote_RightPop_factor)) 
data_SI15 <- bind_rows(rural_have_no_voice2_pop,
                                          rural_have_no_influence_pop, 
                                          distant_people_local__noturban_pop,
                                          distant_people_local_pop,
                                          .id="Characteristic")
data_SI15$Characteristic<-factor(data_SI15$Characteristic, 
                                                    levels=c(1,2,3,4),
                                                    labels=c("*Rural resentment (no say)",
                                                             "Rural resentment (no influence)",
                                                             "*Community disint (excl. big city residents)",
                                                             "Community disint (incl. big city residents)"))

data_SI15$vote_RightPop_factor<-factor(data_SI15$vote_RightPop_factor)
data_SI15$vote_RightPop_factor <- relevel(data_SI15$vote_RightPop_factor, ref = "Right Wing Populist Parties")

Fig_SI15<-data_SI15 %>%
  ggplot()+aes(x=Characteristic,y=n,label=n,fill= vote_RightPop_factor,colour= vote_RightPop_factor)+
  geom_col(alpha=0.9,width=0.5, position = position_dodge(width=0.7))+
  geom_errorbar(aes(ymin = n, 
                    ymax = n_upp), position = position_dodge(width=0.7),
                width = 0.5, lwd=0.4, color="gray40") +
  scale_fill_manual(values = c("#A20021", "#97C1D1"))+
  scale_colour_manual(values = c("#A20021", "#97C1D1"))+
  scale_y_continuous(labels = percent_format(accuracy = 1)) +
  labs(x = " ", y = "", subtitle = "", title="", 
       fill = "", color = "") +  coord_flip()+
  theme_minimal() +facet_wrap(facets=~cntry,nrow=2)+
  theme(legend.position = "bottom",  
        text = element_text(size = 13),
        axis.text.x = element_text(size = 9),
        axis.text.y = element_text(size = 11),
        plot.background = element_rect(fill = "white", colour = "white"),
        plot.margin = unit(c(0, 1, 0.5, 0), "cm"),
        panel.spacing = unit(1, "lines"))
Fig_SI15


ggsave(Fig_SI15, dpi = 600,
       filename = paste0(plotpath, "Fig_SI15.tif"), device = "tiff",
       height = 6, width = 12)

## ---------------------- Figure  SI-16 Social Status - 2009 ISSP Data --------
# use data file ISSP_2009_raw_data.rds
ISSP_2009_data <- readRDS("data/ISSP_2009_raw_data.rds")


# Create a new column 'Country' with NA as default values
ISSP_2009_data$Country <- NA
# Replace values conditionally
ISSP_2009_data$Country[ISSP_2009_data$V4 == 208] <- "Denmark"
ISSP_2009_data$Country[ISSP_2009_data$V4 == 250] <- "France"
ISSP_2009_data$Country[ISSP_2009_data$V4 == 348] <- "Hungary"
ISSP_2009_data$Country[ISSP_2009_data$V4 == 752] <- "Sweden"
ISSP_2009_data$Country[ISSP_2009_data$V4 == 756] <- "Switzerland"
ISSP_2009_data$Country[ISSP_2009_data$V4 == 616] <- "Poland"
ISSP_2009_data$Country[ISSP_2009_data$V4 == 380] <- "Italy"

glimpse(ISSP_2009_data)
# Recode CH_PRTY
ISSP_2009_data$RWP_CH <- 0
ISSP_2009_data$RWP_CH[ISSP_2009_data$CH_PRTY %in% c(4, 11, 12)] <- 1
ISSP_2009_data$RWP_CH[is.na(ISSP_2009_data$CH_PRTY)] <- NA
ISSP_2009_data$RWP_CH[ISSP_2009_data$CH_PRTY %in% c(0, 96, 990)] <- NA
# Recode IT_PRTY
ISSP_2009_data$RWP_IT <- 0
ISSP_2009_data$RWP_IT[ISSP_2009_data$IT_PRTY %in% c(8,9)] <- 1
ISSP_2009_data$RWP_IT[is.na(ISSP_2009_data$IT_PRTY)] <- NA
ISSP_2009_data$RWP_IT[ISSP_2009_data$IT_PRTY %in% c(0, 96, 99, 990)] <- NA
# Recode DK_PRTY
ISSP_2009_data$RWP_DK <- 0
ISSP_2009_data$RWP_DK[ISSP_2009_data$DK_PRTY %in% c(6)] <- 1
ISSP_2009_data$RWP_DK[is.na(ISSP_2009_data$DK_PRTY)] <- NA
ISSP_2009_data$RWP_DK[ISSP_2009_data$DK_PRTY %in% c(0, 96, 99)] <- NA
# Recode IT_PRTY
ISSP_2009_data$RWP_FR <- 0
ISSP_2009_data$RWP_FR[ISSP_2009_data$FR_PRTY %in% c(7)] <- 1
ISSP_2009_data$RWP_FR[is.na(ISSP_2009_data$FR_PRTY)] <- NA
ISSP_2009_data$RWP_FR[ISSP_2009_data$FR_PRTY %in% c(0, 96, 99)] <- NA
# Recode HU_PRTY
ISSP_2009_data$RWP_HU <- 0
ISSP_2009_data$RWP_HU[ISSP_2009_data$HU_PRTY %in% c(9)] <- 1
ISSP_2009_data$RWP_HU[is.na(ISSP_2009_data$HU_PRTY)] <- NA
ISSP_2009_data$RWP_HU[ISSP_2009_data$HU_PRTY %in% c(0, 96, 99)] <- NA
# Recode PL_PRTY
ISSP_2009_data$RWP_PL <- 0
ISSP_2009_data$RWP_PL[ISSP_2009_data$PL_PRTY %in% c(8)] <- 1
ISSP_2009_data$RWP_PL[is.na(ISSP_2009_data$PL_PRTY)] <- NA
ISSP_2009_data$RWP_PL[ISSP_2009_data$PL_PRTY %in% c(0, 96, 99)] <- NA
# Recode SE_PRTY
ISSP_2009_data$RWP_SE <- 0
ISSP_2009_data$RWP_SE[ISSP_2009_data$SE_PRTY %in% c(7)] <- 1
ISSP_2009_data$RWP_SE[is.na(ISSP_2009_data$SE_PRTY)] <- NA
ISSP_2009_data$RWP_SE[ISSP_2009_data$SE_PRTY %in% c(0, 99)] <- NA


# Generate RWP
ISSP_2009_data$RWP <- NA
ISSP_2009_data$RWP[ISSP_2009_data$RWP_CH==1]<-1
ISSP_2009_data$RWP[ISSP_2009_data$RWP_CH==0]<-0

ISSP_2009_data$RWP[ISSP_2009_data$RWP_IT==1]<-1
ISSP_2009_data$RWP[ISSP_2009_data$RWP_IT==0]<-0

ISSP_2009_data$RWP[ISSP_2009_data$RWP_DK==1]<-1
ISSP_2009_data$RWP[ISSP_2009_data$RWP_DK==0]<-0

ISSP_2009_data$RWP[ISSP_2009_data$RWP_FR==1]<-1
ISSP_2009_data$RWP[ISSP_2009_data$RWP_FR==0]<-0

ISSP_2009_data$RWP[ISSP_2009_data$RWP_HU==1]<-1
ISSP_2009_data$RWP[ISSP_2009_data$RWP_HU==0]<-0

ISSP_2009_data$RWP[ISSP_2009_data$RWP_PL==1]<-1
ISSP_2009_data$RWP[ISSP_2009_data$RWP_PL==0]<-0

ISSP_2009_data$RWP[ISSP_2009_data$RWP_SE==1]<-1
ISSP_2009_data$RWP[ISSP_2009_data$RWP_SE==0]<-0
glimpse(ISSP_2009_data)

# Respondent
ISSP_2009_data$SocStat_R <- ISSP_2009_data$V44
ISSP_2009_data$SocStat_R[ISSP_2009_data$V44 %in% c(97, 98, 99)] <- NA

# Respondent's father
ISSP_2009_data$SocStat_F <- ISSP_2009_data$V45
ISSP_2009_data$SocStat_F[ISSP_2009_data$V45 %in% c(97, 98, 99)] <- NA


# Generate SocStat_R25 
ISSP_2009_data$SocStat_R25<-0
ISSP_2009_data$SocStat_R25[ISSP_2009_data$SocStat_R==2   |
                             ISSP_2009_data$SocStat_R==3 |
                             ISSP_2009_data$SocStat_R==4 |
                             ISSP_2009_data$SocStat_R==5 ]<-1
ISSP_2009_data$SocStat_R25[is.na(ISSP_2009_data$SocStat_R)]<-NA
ISSP_2009_data$SocStat_R25[ISSP_2009_data$SocStat_R==0  |
                             ISSP_2009_data$SocStat_R==97 |
                             ISSP_2009_data$SocStat_R==98 |
                             ISSP_2009_data$SocStat_R==99]<-NA
table(ISSP_2009_data$SocStat_R25)


# Generate SocStat_R24
ISSP_2009_data$SocStat_R24<-0
ISSP_2009_data$SocStat_R24[ISSP_2009_data$SocStat_R==2   |
                             ISSP_2009_data$SocStat_R==3 |
                             ISSP_2009_data$SocStat_R==4 ]<-1
ISSP_2009_data$SocStat_R24[is.na(ISSP_2009_data$SocStat_R)]<-NA
ISSP_2009_data$SocStat_R24[ISSP_2009_data$SocStat_R==0  |
                             ISSP_2009_data$SocStat_R==98 |
                             ISSP_2009_data$SocStat_R==99]<-NA
table(ISSP_2009_data$SocStat_R24)


glimpse(ISSP_2009_data)
ISSP_2009_data$Country<-factor(ISSP_2009_data$Country)
ISSP_2009_data$Party<-factor(ISSP_2009_data$RWP, levels=c(1,0), 
                             labels=c("Right-wing populist parties","Other parties"))

calculate_mean <- function(var, data) {
  var_name <- as.name(var)
  data %>%
    dplyr::filter(!is.na(!!var_name)) %>%
    dplyr::filter(!is.na(Party)) %>%
    as_survey_design(weights = c(WEIGHT)) %>%
    dplyr::group_by(Country,Party) %>%
    dplyr::summarize(n = survey_mean(!!var_name, na.rm = FALSE, vartype = "ci"))
}

SocStat_R24_2009pop <- calculate_mean("SocStat_R24", ISSP_2009_data)
SocStat_R25_2009pop <- calculate_mean("SocStat_R25", ISSP_2009_data)



FigSI16_R24<-SocStat_R24_2009pop %>%
  ggplot()+aes(x=Country,y=n,fill=Party,colour=Party)+
  geom_col(alpha=0.9,width=0.5, position = position_dodge(width=0.7))+
  geom_errorbar(aes(ymin = n, 
                    ymax = n_upp), position = position_dodge(width=0.7),
                width = 0.5, lwd=0.4, color="gray40") +
  scale_fill_manual(values = c( "#A20021", "#97C1D1"))+
  scale_colour_manual(values =  c( "#A20021", "#97C1D1"))+
  labs(x = " ", y = "",
       fill = "", color = "") +  coord_flip()+
  theme_minimal() +
  theme(legend.position = "bottom",
        text=element_text(size=13.5),
        panel.spacing = unit(1.7, "lines"))
FigSI16_R24

ggsave(FigSI16_R24, dpi = 600,
       filename = paste0(plotpath, "Fig_SI16_R24.tif"), device = "tiff",
       height = 5, width = 6)


FigSI16_R25<-SocStat_R25_2009pop %>%
  ggplot()+aes(x=Country,y=n,fill=Party,colour=Party)+
  geom_col(alpha=0.9,width=0.5, position = position_dodge(width=0.7))+
  geom_errorbar(aes(ymin = n, 
                    ymax = n_upp), position = position_dodge(width=0.7),
                width = 0.5, lwd=0.4, color="gray40") +
  scale_fill_manual(values = c( "#A20021", "#97C1D1"))+
  scale_colour_manual(values =  c( "#A20021", "#97C1D1"))+
  labs(x = " ", y = "",
       fill = "", color = "") +  coord_flip()+
  theme_minimal() +
  theme(legend.position = "bottom",
        text=element_text(size=13.5),
        panel.spacing = unit(1.7, "lines"))
FigSI16_R25

ggsave(FigSI16_R25, dpi = 600,
       filename = paste0(plotpath, "Fig_SI16_R25.tif"), device = "tiff",
       height = 5, width = 6)


## ---------------------- Figure  SI-17 Social Status - 2017 ISSP Data --------
# use datafile: ISSP_2017_raw_data.rds
ISSP_2017_data <- readRDS("data/ISSP_2017_raw_data.rds")

# Create a new column 'Country' with NA as default values
ISSP_2017_data$Country <- NA
# Replace values conditionally
ISSP_2017_data$Country[ISSP_2017_data$country == 208] <- "Denmark"
ISSP_2017_data$Country[ISSP_2017_data$country == 250] <- "France"
ISSP_2017_data$Country[ISSP_2017_data$country == 276] <- "Germany"
ISSP_2017_data$Country[ISSP_2017_data$country == 348] <- "Hungary"
ISSP_2017_data$Country[ISSP_2017_data$country == 752] <- "Sweden"
ISSP_2017_data$Country[ISSP_2017_data$country == 756] <- "Switzerland"
ISSP_2017_data$Country[ISSP_2017_data$country == 840] <- "United States"

# Recode RWP_CH
ISSP_2017_data$RWP_CH <- 0
ISSP_2017_data$RWP_CH[ISSP_2017_data$CH_PRTY %in% c(4, 12, 13)] <- 1
ISSP_2017_data$RWP_CH[is.na(ISSP_2017_data$CH_PRTY)] <- NA
ISSP_2017_data$RWP_CH[ISSP_2017_data$CH_PRTY %in% c(0, 990)] <- NA

# Recode DK_PRTY
ISSP_2017_data$RWP_DK <- 0
ISSP_2017_data$RWP_DK[ISSP_2017_data$DK_PRTY == 6] <- 1
ISSP_2017_data$RWP_DK[is.na(ISSP_2017_data$DK_PRTY)] <- NA
ISSP_2017_data$RWP_DK[ISSP_2017_data$DK_PRTY %in% c(0, 990)] <- NA

# Recode FR_PRTY
ISSP_2017_data$RWP_FR <- 0
ISSP_2017_data$RWP_FR[ISSP_2017_data$FR_PRTY == 9] <- 1
ISSP_2017_data$RWP_FR[is.na(ISSP_2017_data$FR_PRTY)] <- NA
ISSP_2017_data$RWP_FR[ISSP_2017_data$FR_PRTY %in% c(0, 990)] <- NA

# Recode DE_PRTY
ISSP_2017_data$RWP_DE <- 0
ISSP_2017_data$RWP_DE[ISSP_2017_data$DE_PRTY == 6] <- 1
ISSP_2017_data$RWP_DE[is.na(ISSP_2017_data$DE_PRTY)] <- NA
ISSP_2017_data$RWP_DE[ISSP_2017_data$DE_PRTY %in% c(0, 990)] <- NA

# Recode HU_PRTY
ISSP_2017_data$RWP_HU <- 0
ISSP_2017_data$RWP_HU[ISSP_2017_data$HU_PRTY %in% c(1, 3)] <- 1
ISSP_2017_data$RWP_HU[is.na(ISSP_2017_data$HU_PRTY)] <- NA
ISSP_2017_data$RWP_HU[ISSP_2017_data$HU_PRTY %in% c(0, 990)] <- NA

# Recode SE_PRTY
ISSP_2017_data$RWP_SE <- 0
ISSP_2017_data$RWP_SE[ISSP_2017_data$SE_PRTY == 7] <- 1
ISSP_2017_data$RWP_SE[is.na(ISSP_2017_data$SE_PRTY)] <- NA
ISSP_2017_data$RWP_SE[ISSP_2017_data$SE_PRTY %in% c(0, 990)] <- NA

# Recode US_PRTY
ISSP_2017_data$RWP_US <- 0
ISSP_2017_data$RWP_US[ISSP_2017_data$US_PRTY == 6] <- 1
ISSP_2017_data$RWP_US[is.na(ISSP_2017_data$US_PRTY)] <- NA
ISSP_2017_data$RWP_US[ISSP_2017_data$US_PRTY %in% c(0, 990)] <- NA

# Generate RWP
ISSP_2017_data$RWP <- NA
ISSP_2017_data$RWP[ISSP_2017_data$RWP_CH==1]<-1
ISSP_2017_data$RWP[ISSP_2017_data$RWP_CH==0]<-0

ISSP_2017_data$RWP[ISSP_2017_data$RWP_DK==1]<-1
ISSP_2017_data$RWP[ISSP_2017_data$RWP_DK==0]<-0

ISSP_2017_data$RWP[ISSP_2017_data$RWP_FR==1]<-1
ISSP_2017_data$RWP[ISSP_2017_data$RWP_FR==0]<-0

ISSP_2017_data$RWP[ISSP_2017_data$RWP_DE==1]<-1
ISSP_2017_data$RWP[ISSP_2017_data$RWP_DE==0]<-0

ISSP_2017_data$RWP[ISSP_2017_data$RWP_HU==1]<-1
ISSP_2017_data$RWP[ISSP_2017_data$RWP_HU==0]<-0

ISSP_2017_data$RWP[ISSP_2017_data$RWP_SE==1]<-1
ISSP_2017_data$RWP[ISSP_2017_data$RWP_SE==0]<-0

ISSP_2017_data$RWP[ISSP_2017_data$RWP_US==1]<-1
ISSP_2017_data$RWP[ISSP_2017_data$RWP_US==0]<-0

# Generate SocStat_R25 
ISSP_2017_data$SocStat_R25<-0
ISSP_2017_data$SocStat_R25[ISSP_2017_data$TOPBOT==2   |
                             ISSP_2017_data$TOPBOT==3 |
                             ISSP_2017_data$TOPBOT==4 |
                             ISSP_2017_data$TOPBOT==5 ]<-1
ISSP_2017_data$SocStat_R25[is.na(ISSP_2017_data$TOPBOT)]<-NA
ISSP_2017_data$SocStat_R25[ISSP_2017_data$TOPBOT==0  |
                             ISSP_2017_data$TOPBOT==98 |
                             ISSP_2017_data$TOPBOT==99]<-NA
table(ISSP_2017_data$SocStat_R25)

# Generate SocStat_R24 
ISSP_2017_data$SocStat_R24<-0
ISSP_2017_data$SocStat_R24[ISSP_2017_data$TOPBOT==2   |
                             ISSP_2017_data$TOPBOT==3 |
                             ISSP_2017_data$TOPBOT==4 ]<-1
ISSP_2017_data$SocStat_R24[is.na(ISSP_2017_data$TOPBOT)]<-NA
ISSP_2017_data$SocStat_R24[ISSP_2017_data$TOPBOT==0  |
                             ISSP_2017_data$TOPBOT==98 |
                             ISSP_2017_data$TOPBOT==99]<-NA
table(ISSP_2017_data$SocStat_R24)



ISSP_2017_data$Country<-factor(ISSP_2017_data$Country)
ISSP_2017_data$Party<-factor(ISSP_2017_data$RWP, levels=c(1,0), 
                             labels=c("Right-wing populist parties","Other parties"))

calculate_mean <- function(var, data) {
  var_name <- as.name(var)
  data %>%
    dplyr::filter(!is.na(!!var_name)) %>%
    dplyr::filter(!is.na(Party)) %>%
    as_survey_design(weights = c(WEIGHT)) %>%
    dplyr::group_by(Country,Party) %>%
    dplyr::summarize(n = survey_mean(!!var_name, na.rm = FALSE, vartype = "ci"))
}

SocStat_R24_pop <- calculate_mean("SocStat_R24", ISSP_2017_data)
SocStat_R25_pop <- calculate_mean("SocStat_R25", ISSP_2017_data)


FigSI17_R25<-SocStat_R25_pop %>%
  ggplot()+aes(x=Country,y=n,fill=Party,colour=Party)+
  geom_col(alpha=0.9,width=0.5, position = position_dodge(width=0.7))+
  geom_errorbar(aes(ymin = n, 
                    ymax = n_upp), position = position_dodge(width=0.7),
                width = 0.5, lwd=0.4, color="gray40") +
  scale_fill_manual(values = c( "#A20021", "#97C1D1"))+
  scale_colour_manual(values =  c( "#A20021", "#97C1D1"))+
  labs(x = " ", y = "",fill = "", color = "") +  coord_flip()+
  theme_minimal() +
  theme(legend.position = "bottom",
        text=element_text(size=13.5),
        panel.spacing = unit(1.7, "lines"))
FigSI17_R25

ggsave(FigSI17_R25, dpi = 600,
       filename = paste0(plotpath, "Fig_SI17_R25.tif"), device = "tiff",
       height = 5, width = 6)



FigSI17_R24<-SocStat_R24_pop %>%
  ggplot()+aes(x=Country,y=n,fill=Party,colour=Party)+
  geom_col(alpha=0.9,width=0.5, position = position_dodge(width=0.7))+
  geom_errorbar(aes(ymin = n, 
                    ymax = n_upp), position = position_dodge(width=0.7),
                width = 0.5, lwd=0.4, color="gray40") +
  scale_fill_manual(values = c( "#A20021", "#97C1D1"))+
  scale_colour_manual(values =  c( "#A20021", "#97C1D1"))+
  labs(x = " ", y = "",
       fill = "", color = "") +  coord_flip()+
  theme_minimal() +
  theme(legend.position = "bottom",
        text=element_text(size=13.5),
        panel.spacing = unit(1.7, "lines"))
FigSI17_R24

ggsave(FigSI17_R24, dpi = 600,
       filename = paste0(plotpath, "Fig_SI17_R24.tif"), device = "tiff",
       height = 5, width = 6)

## ---------------------- Figure  SI-18 Social Status Decline - 2009 ISSP Data -----------
# use the revised data (ISSP_2009_data) with the new variables based on the raw ISSP_2009_raw_data (alr)

ISSP_2009_data$SocStat_compFam<-ISSP_2009_data$SocStat_R-ISSP_2009_data$SocStat_F
ISSP_2009_data$SocStat_compFam[is.na(ISSP_2009_data$SocStat_R)]<-NA
ISSP_2009_data$SocStat_compFam[is.na(ISSP_2009_data$SocStat_F)]<-NA

ISSP_2009_data$SocStat_declined<-NA
ISSP_2009_data$SocStat_declined[ISSP_2009_data$SocStat_compFam >= -9 & 
                                  ISSP_2009_data$SocStat_compFam <= -1]<-1
ISSP_2009_data$SocStat_declined[ISSP_2009_data$SocStat_compFam >= 0 & 
                                  ISSP_2009_data$SocStat_compFam <= 9] <- 0

calculate_mean <- function(var, data) {
  var_name <- as.name(var)
  data %>%
    dplyr::filter(!is.na(!!var_name)) %>%
    dplyr::filter(!is.na(Party)) %>%
    as_survey_design(weights = c(WEIGHT)) %>%
    dplyr::group_by(Country,Party) %>%
    dplyr::summarize(n = survey_mean(!!var_name, na.rm = FALSE, vartype = "ci"))
}

SocStat_declined_pop <- calculate_mean("SocStat_declined", ISSP_2009_data)



Fig_SI18<-SocStat_declined_pop %>%
  ggplot()+aes(x=Country,y=n,fill=Party,colour=Party)+
  geom_col(alpha=0.9,width=0.5, position = position_dodge(width=0.7))+
  geom_errorbar(aes(ymin = n, 
                    ymax = n_upp), position = position_dodge(width=0.7),
                width = 0.5, lwd=0.4, color="gray40") +
  scale_fill_manual(values = c( "#A20021", "#97C1D1"))+
  scale_colour_manual(values =  c( "#A20021", "#97C1D1"))+
  labs(x = " ", y = "",
       fill = "", color = "") +  coord_flip()+
  theme_minimal() +
  theme(legend.position = "bottom",
        text=element_text(size=13.5),
        panel.spacing = unit(1.7, "lines"))
Fig_SI18

ggsave(Fig_SI18, dpi = 600,
       filename = paste0(plotpath, "Fig_SI18.tif"), device = "tiff",
       height = 5, width = 6)

## ---------------------- Figure  SI-19 Share of voters who match the community disintegration storyline, by vote --------
# Uploud data: EVS_WVS_raw_data.rds
EVS_WVS_data <- readRDS("data/EVS_WVS_raw_data.rds")
EVS_WVS_data$cntry_AN<-factor(EVS_WVS_data$cntry_AN, levels = c("CH", "DE", "DK", "FR", "GB",
                                                                    "HU", "IT","NL", "PL", "SE", "US"),
                                labels = c("Switzerland","Germany", "Denmark","France",
                                           "United Kingdom","Hungary",
                                           "Italy","Netherlands",
                                           "Poland","Sweden", "United States"))

# Codes right-wing populist

code_vote_choice <- function(df) {
  df <- df %>%
    mutate(
      vote_choice = case_when(
        # DK -------------
        E181_EVS5  %in% c(20801:20804,20806:20810) ~ 0,
        E181_EVS5  %in% c(20805)                   ~ 1, # 20805 DK: Danish Peoples Party
        E181_EVS5  %in% c(20811)                   ~ 2, #DK: Blank vote
        E181_EVS5  %in% c(20866)                   ~ 3, #DK: No [no other] party appeals to me
        
        # FR -------------
        E181_EVS5  %in% c(25002:20804,25015:25026) ~ 0,
        E181_EVS5  %in% c(25014)                   ~ 1, # 25014 FR: National Front
        E181_EVS5  %in% c(25066)                   ~ 3, #DK: No [no other] party appeals to me
        
        # DE -------------
        E181_EVS5  %in% c(27601:27605,27607) ~ 0,
        E181_EVS5  %in% c(27606)                   ~ 1, # 27606 DE: Alternative for Germany
        E181_EVS5  %in% c(27666)                   ~ 3, #DK: No [no other] party appeals to me
        
        
        
        E179_WVS7  %in% c(276001:276004,276033,276034) ~ 0,
        E179_WVS7  %in% c(27606)                   ~ 1, #  276033 DEU: Alternative for Germany 
        
        # HU -------------
        E181_EVS5  %in% c(34801,34803,34805, 34806:34826) ~ 0,
        E181_EVS5  %in% c(34802, 34804)                   ~ 1, #34802 HU: Fidesz 34804; Movement for a Better Hungary (Jobbik)
        E181_EVS5  %in% c(34866)                   ~ 3, #DK: No [no other] party appeals to me
        
        # IT -------------
        E181_EVS5  %in% c(38001:38008,38010:38012, 38015:38031, 38009) ~ 0,
        E181_EVS5  %in% c(38013, 38014)                   ~ 1, #38013 IT: League, 38014 Brothers of Italy 
        E181_EVS5  %in% c(38066)                   ~ 3, #DK: No [no other] party appeals to me
        
        
        # NL  -------------
        E181_EVS5  %in% c(52801,52803:52810, 52812:52814) ~ 0,
        E181_EVS5  %in% c(52802,52811)                   ~ 1, #52802 NL: Party for Freedom, 52811 NL: Reformed Political Party
        E181_EVS5  %in% c(52866)                   ~ 3, #DK: No [no other] party appeals to me
        
        
        # PL  -------------
        
        E181_EVS5  %in% c(61602:61609) ~ 0,
        E181_EVS5  %in% c(61601)                   ~ 1, #61601 PL: Law and Justice
        E181_EVS5  %in% c(61666)                   ~ 3, #DK: No [no other] party appeals to me
        
        
        # SE  -------------
        
        E181_EVS5  %in% c(75201:75202, 75204:75231) ~ 0,
        E181_EVS5  %in% c(75203)                   ~ 1, #75203 SE: Sweden democrats
        E181_EVS5  %in% c(75266)                   ~ 3, #DK: No [no other] party appeals to me
        
        # CH ------------
        E181_EVS5  %in% c(75601:75603, 75605:75610, 75612, 75614:75626) ~ 0,
        E181_EVS5  %in% c(75604, 75611, 75613)                   ~ 1, #75604 CH: Swiss People's Party, 75611 CH: Federal Democratic Union, 75613 CH: Ticino League
        E181_EVS5  %in% c(75666)                   ~ 3, #DK: No [no other] party appeals to me
        
        
        # GB ------------
        E181_EVS5  %in% c(82601:82606, 82609:82609, 82608) ~ 0,
        E181_EVS5  %in% c(82607)                   ~ 1, # 82607 GB: UK Independence Party (UKIP)  82607
        E181_EVS5  %in% c(82666)                   ~ 3, #DK: No [no other] party appeals to me
        
        
        # US ------------
        
        E179_WVS7  %in% c(840002:840004, 840006, 5) ~ 0, #5=Other
        E179_WVS7  %in% c(840001)                   ~ 1, 
        E179_WVS7  %in% c(82666)                   ~ 3, #DK: No [no other] party appeals to me
        
      ))}

EVS_WVS_data <- code_vote_choice(EVS_WVS_data)
EVS_WVS_data<-subset(EVS_WVS_data, vote_choice==1 | vote_choice==0)


# G255 How close you feel: Your village, town  or city (1 Very close 2 Close 3 Not very close 4 Not close at all)

EVS_WVS_data$distant_people_local_noturban<-0
EVS_WVS_data$distant_people_local_noturban[EVS_WVS_data$G255==3|
                                           EVS_WVS_data$G255==4 ]<-1
EVS_WVS_data$distant_people_local_noturban[EVS_WVS_data$size_5c==5 ]<-0
EVS_WVS_data$distant_people_local_noturban[is.na(EVS_WVS_data$size_5c)]<-NA
EVS_WVS_data$distant_people_local_noturban[is.na(EVS_WVS_data$G255)]<-NA


Fig_SI19_data <- EVS_WVS_data %>%
  dplyr::filter(!is.na(distant_people_local_noturban)) %>%
  as_survey_design(weights = c(pwght)) %>%
  dplyr::group_by(cntry_AN, vote_choice) %>%
  dplyr::summarize(n = survey_mean(distant_people_local_noturban, na.rm = FALSE, vartype = "ci")) %>%
  filter(!is.na(vote_choice)) 
  
Fig_SI19_data$vote_choice<-factor(Fig_SI19_data$vote_choice, 
                                   levels=c(0,1),labels =c("Other Parties","Populist Parties"))

Fig_SI19<-Fig_SI19_data %>%
   filter(cntry_AN !="United Kingdom") %>%
   filter(cntry_AN !="Netherlands") %>%
  mutate(cntry_AN = fct_reorder(cntry_AN, desc(n))) %>%
  ggplot()+aes(x=cntry_AN,y=n,label=n,fill=vote_choice,colour=vote_choice)+
  geom_col(alpha=0.9,width=0.5, position = position_dodge(width=0.7))+
  geom_errorbar(aes(ymin = n, 
                    ymax = n_upp), position = position_dodge(width=0.7),
                width = 0.5, lwd=0.3, color="gray40") +
  scale_fill_manual(values = c("#97C1D1", "#A20021"))+
  scale_colour_manual(values = c("#97C1D1", "#A20021"))+
  scale_y_continuous(limit=c(0, 0.4), 
                     labels = scales::percent_format(accuracy = 1))+
  labs(x = " ", y = "", fill = "", color = "") +  coord_flip()+
  theme_minimal() +     theme(legend.position = "bottom",
                              text=element_text( size=13.5),
                              panel.spacing = unit(1.9, "lines"))
Fig_SI19


ggsave(Fig_SI19, dpi = 600,
       filename = paste0(plotpath, "Fig_SI19.tif"), device = "tiff",
       height = 5, width = 6)

